@echo off
setlocal EnableExtensions EnableDelayedExpansion

set "SCRIPT_DIR=%~dp0"
cd /d "%SCRIPT_DIR%"

set "FRPC_EXE=%SCRIPT_DIR%frpc.exe"
set "CONFIG_FILE=%SCRIPT_DIR%frpc.toml"
set "PID_FILE=%SCRIPT_DIR%frpc.pid"
set "LOG_FILE=%SCRIPT_DIR%frpc.log"
set "STARTUP_INSTALLER=%SCRIPT_DIR%install_startup.bat"
set "STARTUP_REMOVER=%SCRIPT_DIR%uninstall_startup.bat"

if "%~1"=="" goto :usage

set "ACTION=%~1"

if /I "%ACTION%"=="start" goto :start
if /I "%ACTION%"=="autostart" goto :start_silent
if /I "%ACTION%"=="stop" goto :stop
if /I "%ACTION%"=="restart" goto :restart
if /I "%ACTION%"=="status" goto :status
if /I "%ACTION%"=="logs" goto :logs
if /I "%ACTION%"=="config" goto :config
if /I "%ACTION%"=="list" goto :list
if /I "%ACTION%"=="install-startup" goto :install_startup
if /I "%ACTION%"=="uninstall-startup" goto :uninstall_startup
if /I "%ACTION%"=="help" goto :usage

echo Unknown command: %ACTION%
echo.
goto :usage

:ensure_files
if not exist "%FRPC_EXE%" (
    echo Error: frpc.exe not found
    echo Put the Windows frpc.exe in:
    echo   %FRPC_EXE%
    exit /b 1
)
if not exist "%CONFIG_FILE%" (
    echo Error: config file not found
    echo Expected:
    echo   %CONFIG_FILE%
    exit /b 1
)
exit /b 0

:get_pid
set "FRPC_PID="
if exist "%PID_FILE%" (
    set /p FRPC_PID=<"%PID_FILE%"
)
exit /b 0

:is_running
set "FRPC_PID="
if not exist "%FRPC_EXE%" exit /b 1
for /f "usebackq delims=" %%i in (`powershell -NoProfile -ExecutionPolicy Bypass -Command "$target = (Resolve-Path $env:FRPC_EXE -ErrorAction SilentlyContinue).Path; if (-not $target) { exit 1 }; $pidPath = $env:PID_FILE; $pidText = ''; if (Test-Path $pidPath) { $pidText = (Get-Content -Path $pidPath -TotalCount 1 -ErrorAction SilentlyContinue).Trim() }; if ($pidText -match '^\d+$') { $p = Get-CimInstance Win32_Process -Filter \"ProcessId=$pidText\" -ErrorAction SilentlyContinue; if ($p -and $p.Name -eq 'frpc.exe' -and $p.ExecutablePath -eq $target) { [Console]::Write($p.ProcessId); exit 0 } }; $p = Get-CimInstance Win32_Process -Filter \"Name='frpc.exe'\" -ErrorAction SilentlyContinue | Where-Object { $_.ExecutablePath -eq $target } | Select-Object -First 1; if ($p) { [Console]::Write($p.ProcessId); exit 0 }; exit 1"`) do set "FRPC_PID=%%i"
if defined FRPC_PID (
    >"%PID_FILE%" echo %FRPC_PID%
    exit /b 0
)
if exist "%PID_FILE%" del /f /q "%PID_FILE%" >nul 2>nul
exit /b 1

:start
call :ensure_files || exit /b 1
call :is_running
if not errorlevel 1 (
    echo FRP client is already running. PID=%FRPC_PID%
    exit /b 0
)

echo Starting FRP client in background...
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$p = Start-Process -FilePath $env:FRPC_EXE -ArgumentList @('-c',$env:CONFIG_FILE) -WindowStyle Hidden -PassThru; Start-Sleep -Seconds 2; if ($p.HasExited) { exit 1 } else { Set-Content -Path $env:PID_FILE -Value $p.Id; exit 0 }"
if errorlevel 1 (
    echo Start failed. Check log:
    echo   %LOG_FILE%
    exit /b 1
)

call :get_pid
echo Started. PID=%FRPC_PID%
echo Server entry: laser.ranging.hb-mz.com:443
exit /b 0

:start_silent
call :ensure_files || exit /b 1
call :is_running
if not errorlevel 1 exit /b 0

powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$p = Start-Process -FilePath $env:FRPC_EXE -ArgumentList @('-c',$env:CONFIG_FILE) -WindowStyle Hidden -PassThru; Start-Sleep -Seconds 2; if (-not $p.HasExited) { Set-Content -Path $env:PID_FILE -Value $p.Id }"
exit /b 0

:stop
call :is_running
if errorlevel 1 (
    echo FRP client is not running.
    exit /b 0
)

echo Stopping FRP client. PID=%FRPC_PID%
taskkill /PID %FRPC_PID% /T /F >nul 2>nul
if exist "%PID_FILE%" del /f /q "%PID_FILE%" >nul 2>nul
echo Stopped.
exit /b 0

:restart
call :stop
echo.
call :start
exit /b %ERRORLEVEL%

:status
call :is_running
if errorlevel 1 (
    echo FRP client is not running.
    exit /b 1
)
echo FRP client is running.
echo PID: %FRPC_PID%
echo Config: %CONFIG_FILE%
echo Log: %LOG_FILE%
echo Server entry: laser.ranging.hb-mz.com:443
powershell -NoProfile -Command "Get-Process -Id $env:FRPC_PID | Select-Object Id, ProcessName, Path"
exit /b 0

:logs
if not exist "%LOG_FILE%" (
    echo Log file not found:
    echo   %LOG_FILE%
    exit /b 1
)
echo Last 50 log lines:
powershell -NoProfile -Command "Get-Content -Path $env:LOG_FILE -Tail 50"
exit /b 0

:config
if not exist "%CONFIG_FILE%" (
    echo Config file not found:
    echo   %CONFIG_FILE%
    exit /b 1
)
type "%CONFIG_FILE%"
exit /b 0

:list
if not exist "%CONFIG_FILE%" (
    echo Config file not found:
    echo   %CONFIG_FILE%
    exit /b 1
)
echo Proxy list:
echo ----------------------------------------
powershell -NoProfile -Command ^
  "$name=''; $type=''; $localIp=''; $localPort=''; $remotePort='';" ^
  "foreach ($line in Get-Content $env:CONFIG_FILE) {" ^
  "  $t = $line.Trim();" ^
  "  if ($t -eq '[[proxies]]') {" ^
  "    if ($name) { Write-Host ('Name: ' + $name); Write-Host ('Type: ' + $type); Write-Host ('Local: ' + $localIp + ':' + $localPort); Write-Host ('Remote: 180.76.176.32:' + $remotePort); Write-Host '' }" ^
  "    $name=''; $type=''; $localIp=''; $localPort=''; $remotePort=''; continue" ^
  "  }" ^
  "  if ($t -match '^name = \"(.+)\"$') { $name=$Matches[1]; continue }" ^
  "  if ($t -match '^type = \"(.+)\"$') { $type=$Matches[1]; continue }" ^
  "  if ($t -match '^localIP = \"(.+)\"$') { $localIp=$Matches[1]; continue }" ^
  "  if ($t -match '^localPort = (.+)$') { $localPort=$Matches[1]; continue }" ^
  "  if ($t -match '^remotePort = (.+)$') { $remotePort=$Matches[1]; continue }" ^
  "}" ^
  "if ($name) { Write-Host ('Name: ' + $name); Write-Host ('Type: ' + $type); Write-Host ('Local: ' + $localIp + ':' + $localPort); Write-Host ('Remote: 180.76.176.32:' + $remotePort) }"
echo ----------------------------------------
exit /b 0

:install_startup
call "%STARTUP_INSTALLER%"
exit /b %ERRORLEVEL%

:uninstall_startup
call "%STARTUP_REMOVER%"
exit /b %ERRORLEVEL%

:usage
echo FRP Windows manager
echo.
echo Usage:
echo   %~nx0 start
echo   %~nx0 stop
echo   %~nx0 restart
echo   %~nx0 status
echo   %~nx0 logs
echo   %~nx0 config
echo   %~nx0 list
echo   %~nx0 install-startup
echo   %~nx0 uninstall-startup
echo.
echo Files:
echo   frpc.exe   Windows client binary
echo   frpc.toml  Config file
echo.
echo Example:
echo   %~nx0 start
exit /b 0
