@echo off
setlocal enabledelayedexpansion
title FFmpeg Installer

echo.
echo ================================================
echo  FFmpeg One-Click Installer
echo  winget - choco - GitHub release fallback
echo ================================================
echo.

:: ----------------------------------------------------------------
:: Step 1: Check if already installed
:: ----------------------------------------------------------------
where ffmpeg >nul 2>&1
if !errorlevel! equ 0 (
    for /f "delims=" %%V in ('ffmpeg -version 2^>nul ^| findstr /B "ffmpeg version"') do (
        echo [OK] FFmpeg already installed:
        echo      %%V
        goto :done_ok
    )
)

:: Check user-local fallback
set "FFMPEG_LOCAL=%USERPROFILE%\.ffmpeg\bin"
if exist "%FFMPEG_LOCAL%\ffmpeg.exe" (
    "%FFMPEG_LOCAL%\ffmpeg.exe" -version >nul 2>&1
    if !errorlevel! equ 0 (
        echo [OK] FFmpeg found at: %FFMPEG_LOCAL%
        echo      Ensuring PATH includes this directory...
        goto :update_path
    )
)

:: ----------------------------------------------------------------
:: Step 2: Try winget
:: ----------------------------------------------------------------
echo [1] Trying winget...
where winget >nul 2>&1
if !errorlevel! equ 0 (
    winget install --id Gyan.FFmpeg -e --silent --accept-package-agreements --accept-source-agreements
    if !errorlevel! equ 0 (
        echo [OK] Installed via winget. Restart your shell to use 'ffmpeg'.
        goto :done_ok
    )
    echo   [SKIP] winget install failed, trying next method...
) else (
    echo   [SKIP] winget not available
)
echo.

:: ----------------------------------------------------------------
:: Step 3: Try choco
:: ----------------------------------------------------------------
echo [2] Trying Chocolatey...
where choco >nul 2>&1
if !errorlevel! equ 0 (
    choco install ffmpeg -y --no-progress
    if !errorlevel! equ 0 (
        echo [OK] Installed via choco. Restart your shell to use 'ffmpeg'.
        goto :done_ok
    )
    echo   [SKIP] choco install failed, trying next method...
) else (
    echo   [SKIP] choco not available
)
echo.

:: ----------------------------------------------------------------
:: Step 4: GitHub release direct download (BtbN/FFmpeg-Builds)
:: ----------------------------------------------------------------
echo [3] Downloading from GitHub (BtbN/FFmpeg-Builds)...
set "INSTALL_DIR=%USERPROFILE%\.ffmpeg"
set "ZIP_FILE=%TEMP%\ffmpeg_release.zip"
set "ZIP_URL=https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip"

mkdir "%INSTALL_DIR%" 2>nul
if exist "%ZIP_FILE%" del /f /q "%ZIP_FILE%" >nul 2>&1

echo   Target: %INSTALL_DIR%
echo   URL:    %ZIP_URL%
echo   (about 60-80MB, may take a few minutes)
echo.

where curl.exe >nul 2>&1
if !errorlevel! equ 0 (
    curl.exe -L -A "MoveStudio-FFmpeg-Installer" -o "%ZIP_FILE%" "%ZIP_URL%"
) else (
    powershell -NoProfile -ExecutionPolicy Bypass -Command "try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -Uri '%ZIP_URL%' -OutFile '%ZIP_FILE%' -UseBasicParsing } catch { Write-Host ('[ERROR] '+$_.Exception.Message); exit 1 }"
)

if not exist "%ZIP_FILE%" goto :download_fail
for %%I in ("%ZIP_FILE%") do set "_DL_SIZE=%%~zI"
if !_DL_SIZE! lss 1048576 goto :download_fail

echo   [OK] Downloaded !_DL_SIZE! bytes
echo.
echo   Extracting...

where tar.exe >nul 2>&1
if !errorlevel! equ 0 (
    tar.exe -xf "%ZIP_FILE%" -C "%INSTALL_DIR%"
) else (
    powershell -NoProfile -ExecutionPolicy Bypass -Command "try { Expand-Archive -Path '%ZIP_FILE%' -DestinationPath '%INSTALL_DIR%' -Force } catch { Write-Host ('[ERROR] '+$_.Exception.Message); exit 1 }"
)
if !errorlevel! neq 0 (
    echo   [ERROR] Extraction failed.
    goto :error_exit
)

del /f /q "%ZIP_FILE%" >nul 2>&1

:: Move extracted bin folder to a stable path
set "FFMPEG_BIN=%INSTALL_DIR%\bin"
if not exist "%FFMPEG_BIN%\ffmpeg.exe" (
    for /d %%D in ("%INSTALL_DIR%\ffmpeg-*") do (
        if exist "%%D\bin\ffmpeg.exe" (
            if exist "%FFMPEG_BIN%" rmdir /s /q "%FFMPEG_BIN%" >nul 2>&1
            move "%%D\bin" "%FFMPEG_BIN%" >nul 2>&1
            rmdir /s /q "%%D" >nul 2>&1
        )
    )
)

if not exist "%FFMPEG_BIN%\ffmpeg.exe" (
    echo   [ERROR] ffmpeg.exe not found after extraction.
    goto :error_exit
)

echo   [OK] Installed to %FFMPEG_BIN%
echo.

:update_path
:: ----------------------------------------------------------------
:: Step 5: Persist PATH (HKCU\Environment) without admin
:: ----------------------------------------------------------------
echo [4] Updating user PATH...
set "FFMPEG_BIN=%USERPROFILE%\.ffmpeg\bin"

:: Read current user PATH from registry, append FFMPEG_BIN if not present
powershell -NoProfile -ExecutionPolicy Bypass -Command "$cur = [Environment]::GetEnvironmentVariable('PATH','User'); if (-not $cur) { $cur = '' }; $bin = '%FFMPEG_BIN%'; if ($cur -notlike ('*' + $bin + '*')) { $new = if ($cur) { $cur.TrimEnd(';') + ';' + $bin } else { $bin }; [Environment]::SetEnvironmentVariable('PATH', $new, 'User'); Write-Host ('  [OK] Appended: ' + $bin) } else { Write-Host '  [OK] Already in PATH' }"

:: Notify Explorer/shells of environment change
powershell -NoProfile -ExecutionPolicy Bypass -Command "$sig = '[DllImport(\"user32.dll\", SetLastError=true, CharSet=CharSet.Auto)]public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);'; $type = Add-Type -MemberDefinition $sig -Name NativeMethods -Namespace Win32 -PassThru; $HWND_BROADCAST = [IntPtr]0xffff; $WM_SETTINGCHANGE = 0x1A; [UIntPtr]$result = [UIntPtr]::Zero; [void]$type::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$result)" >nul 2>&1

echo.

:done_ok
echo ================================================
echo  FFmpeg install finished.
echo  Open a NEW terminal to use 'ffmpeg' command.
echo ================================================
echo.
pause
exit /b 0

:download_fail
echo   [ERROR] Download failed or file too small.
echo   Manual download: %ZIP_URL%

:error_exit
echo.
echo ================================================
echo  FFmpeg install FAILED
echo  Try manual install:
echo    https://www.gyan.dev/ffmpeg/builds/
echo  Or:
echo    https://github.com/BtbN/FFmpeg-Builds/releases
echo ================================================
echo.
pause
exit /b 1
