@echo off
setlocal EnableExtensions
title Updating FFmpeg

set "YTD_DIR=C:\YTD"
set "FFMPEG_DIR=%YTD_DIR%\FFMPEG"
set "WORK_DIR=%YTD_DIR%\_ffmpeg_update"
set "ZIP_FILE=%WORK_DIR%\ffmpeg-release-essentials.zip"
set "HASH_FILE=%WORK_DIR%\ffmpeg-release-essentials.zip.sha256"
set "EXTRACT_DIR=%WORK_DIR%\extracted"
set "ZIP_URL=https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip"
set "HASH_URL=https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip.sha256"
set "SILENT=0"

if /I "%~1"=="/silent" set "SILENT=1"

:: Request administrator privileges when launched manually.
fltmc >nul 2>&1
if errorlevel 1 (
    if "%SILENT%"=="1" exit /b 1
    echo Administrator permission is required.
    powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ^
        "Start-Process -FilePath '%~f0' -Verb RunAs"
    exit /b
)

echo.
echo Downloading the latest FFmpeg release...
echo.

if exist "%WORK_DIR%" rmdir /s /q "%WORK_DIR%"
mkdir "%WORK_DIR%" >nul 2>&1
mkdir "%EXTRACT_DIR%" >nul 2>&1

powershell.exe -NoProfile -ExecutionPolicy Bypass -Command ^
  "$ErrorActionPreference='Stop';" ^
  "$ProgressPreference='SilentlyContinue';" ^
  "[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12;" ^
  "$work='%WORK_DIR%'; $zip='%ZIP_FILE%'; $hashFile='%HASH_FILE%'; $extract='%EXTRACT_DIR%';" ^
  "$dest='%FFMPEG_DIR%'; $backup='%YTD_DIR%\FFMPEG.backup';" ^
  "try {" ^
  "  Invoke-WebRequest -UseBasicParsing -Uri '%ZIP_URL%' -OutFile $zip;" ^
  "  Invoke-WebRequest -UseBasicParsing -Uri '%HASH_URL%' -OutFile $hashFile;" ^
  "  $hashText=(Get-Content -LiteralPath $hashFile -Raw);" ^
  "  $match=[regex]::Match($hashText,'(?i)\b[0-9a-f]{64}\b');" ^
  "  if(-not $match.Success){throw 'The published SHA-256 checksum could not be read.'};" ^
  "  $expected=$match.Value.ToUpperInvariant();" ^
  "  $actual=(Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash.ToUpperInvariant();" ^
  "  if($actual -ne $expected){throw 'The FFmpeg download failed SHA-256 verification.'};" ^
  "  Expand-Archive -LiteralPath $zip -DestinationPath $extract -Force;" ^
  "  $ffmpeg=Get-ChildItem -LiteralPath $extract -Recurse -File -Filter 'ffmpeg.exe' |" ^
  "    Where-Object {$_.Directory.Name -ieq 'bin'} | Select-Object -First 1;" ^
  "  if(-not $ffmpeg){throw 'ffmpeg.exe was not found in the downloaded package.'};" ^
  "  $packageRoot=$ffmpeg.Directory.Parent.FullName;" ^
  "  & $ffmpeg.FullName -version *> $null;" ^
  "  if($LASTEXITCODE -ne 0){throw 'The downloaded FFmpeg executable could not be started.'};" ^
  "  if(Test-Path -LiteralPath $backup){Remove-Item -LiteralPath $backup -Recurse -Force};" ^
  "  if(Test-Path -LiteralPath $dest){Move-Item -LiteralPath $dest -Destination $backup -Force};" ^
  "  Copy-Item -LiteralPath $packageRoot -Destination $dest -Recurse -Force;" ^
  "  & (Join-Path $dest 'bin\ffmpeg.exe') -version *> $null;" ^
  "  if($LASTEXITCODE -ne 0){throw 'The updated FFmpeg installation could not be verified.'};" ^
  "  if(Test-Path -LiteralPath $backup){Remove-Item -LiteralPath $backup -Recurse -Force};" ^
  "  if(Test-Path -LiteralPath $work){Remove-Item -LiteralPath $work -Recurse -Force};" ^
  "  exit 0;" ^
  "} catch {" ^
  "  Write-Host '';" ^
  "  Write-Host ('ERROR: ' + $_.Exception.Message);" ^
  "  if((Test-Path -LiteralPath $backup) -and -not (Test-Path -LiteralPath $dest)){" ^
  "    Move-Item -LiteralPath $backup -Destination $dest -Force" ^
  "  };" ^
  "  if(Test-Path -LiteralPath $work){Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue};" ^
  "  exit 1;" ^
  "}"

if errorlevel 1 (
    echo.
    echo The FFmpeg update did not complete successfully.
    echo The previous FFmpeg installation was preserved when possible.
    echo Check your internet connection and antivirus protection.
    echo.
    if "%SILENT%"=="0" pause
    exit /b 1
)

echo.
echo FFmpeg was updated successfully.
"C:\YTD\FFMPEG\bin\ffmpeg.exe" -version 2>nul | findstr /B /C:"ffmpeg version"
echo.

if "%SILENT%"=="0" pause
exit /b 0
