@echo off
setlocal EnableExtensions EnableDelayedExpansion
chcp 65001 >nul

title CTUMP Exam Kiosk
set "EXAM_URL=https://nptaictump.io.vn/student/exam/start"
set "EXIT_CODE=CTUMP2026"
set "EXIT_PORT=8765"
if not "%~1"=="" set "EXAM_URL=%~1"

set "KIOSK_DIR=%TEMP%\CTUMP_Exam_Kiosk"
set "KIOSK_PROFILE=%KIOSK_DIR%\profile"
set "SIGNAL_FILE=%KIOSK_DIR%\kiosk_exit.signal"
set "SERVER_PS1=%KIOSK_DIR%\ctump_kiosk_exit_server.ps1"
set "EXIT_TOKEN=%RANDOM%%RANDOM%%RANDOM%%RANDOM%"
if not exist "%KIOSK_DIR%" mkdir "%KIOSK_DIR%" >nul 2>nul
if exist "%SIGNAL_FILE%" del /f /q "%SIGNAL_FILE%" >nul 2>nul

call :append_param kiosk 1
call :append_param ctump_kiosk 1
call :append_param kiosk_autostart 1
call :append_param kiosk_exit_url http://127.0.0.1:%EXIT_PORT%/exit?token=%EXIT_TOKEN%

echo Dang chuan bi CTUMP Exam Kiosk...
call :find_browser
if not defined BROWSER (
  echo Khong tim thay Microsoft Edge hoac Google Chrome.
  echo Vui long cai dat Edge hoac Chrome moi nhat roi chay lai file nay.
  pause
  exit /b 1
)

call :write_exit_server
start "CTUMP Kiosk Exit Server" /min powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%SERVER_PS1%" -Port %EXIT_PORT% -Token "%EXIT_TOKEN%" -Signal "%SIGNAL_FILE%"

echo Dang dong cac cua so trinh duyet cu de dam bao che do thi rieng...
taskkill /f /im msedge.exe >nul 2>nul
taskkill /f /im chrome.exe >nul 2>nul
timeout /t 1 /nobreak >nul

echo Dang an thanh taskbar Windows trong thoi gian thi...
taskkill /f /im explorer.exe >nul 2>nul

goto launch_kiosk

:launch_kiosk
if exist "%SIGNAL_FILE%" del /f /q "%SIGNAL_FILE%" >nul 2>nul
echo Dang mo bai thi o che do kiosk...
if /i "%BROWSER_IMAGE%"=="msedge.exe" (
  start "CTUMP Exam Kiosk" "%BROWSER%" --kiosk "%EXAM_URL%" --edge-kiosk-type=fullscreen --user-data-dir="%KIOSK_PROFILE%" --no-first-run --no-default-browser-check --disable-session-crashed-bubble --disable-restore-session-state --disable-background-mode --disable-features=TranslateUI,msEdgeSidebarV2,msHubApps,msDiscoverChatButton --disable-extensions --disable-component-update --noerrdialogs --password-store=basic --overscroll-history-navigation=0 --disable-pinch
) else (
  start "CTUMP Exam Kiosk" "%BROWSER%" --kiosk "%EXAM_URL%" --user-data-dir="%KIOSK_PROFILE%" --no-first-run --no-default-browser-check --disable-session-crashed-bubble --disable-restore-session-state --disable-background-mode --disable-features=TranslateUI --disable-extensions --disable-component-update --noerrdialogs --password-store=basic --overscroll-history-navigation=0 --disable-pinch
)

goto watch_kiosk

:watch_kiosk
timeout /t 1 /nobreak >nul
if exist "%SIGNAL_FILE%" goto normal_exit
tasklist /fi "imagename eq %BROWSER_IMAGE%" | find /i "%BROWSER_IMAGE%" >nul
if errorlevel 1 goto browser_closed
goto watch_kiosk

:browser_closed
echo.
echo Trinh thi kiosk vua bi dong truoc khi nhan tin hieu nop bai.
echo Neu sinh vien chua nop bai, he thong se mo lai kiosk.
set "INPUT_CODE="
set /p INPUT_CODE=Nhap ma giam thi de thoat kiosk, hoac nhan Enter de mo lai: 
if "%INPUT_CODE%"=="%EXIT_CODE%" goto normal_exit
goto launch_kiosk

:normal_exit
echo Dang thoat kiosk va khoi phuc Windows Explorer...
taskkill /f /im %BROWSER_IMAGE% >nul 2>nul
call :restore_explorer
powershell -NoProfile -Command "Get-Process powershell -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowTitle -like '*CTUMP Kiosk Exit Server*' } | Stop-Process -Force" >nul 2>nul
if exist "%SIGNAL_FILE%" del /f /q "%SIGNAL_FILE%" >nul 2>nul
echo Da thoat CTUMP Exam Kiosk an toan.
timeout /t 2 /nobreak >nul
exit /b 0

:restore_explorer
tasklist /fi "imagename eq explorer.exe" | find /i "explorer.exe" >nul
if errorlevel 1 start explorer.exe
exit /b 0

:find_browser
set "EDGE1=%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe"
set "EDGE2=%ProgramFiles%\Microsoft\Edge\Application\msedge.exe"
set "CHROME1=%ProgramFiles%\Google\Chrome\Application\chrome.exe"
set "CHROME2=%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe"
if exist "%EDGE1%" set "BROWSER=%EDGE1%"& set "BROWSER_IMAGE=msedge.exe"& exit /b 0
if exist "%EDGE2%" set "BROWSER=%EDGE2%"& set "BROWSER_IMAGE=msedge.exe"& exit /b 0
if exist "%CHROME1%" set "BROWSER=%CHROME1%"& set "BROWSER_IMAGE=chrome.exe"& exit /b 0
if exist "%CHROME2%" set "BROWSER=%CHROME2%"& set "BROWSER_IMAGE=chrome.exe"& exit /b 0
exit /b 1

:append_param
set "SEP=?"
echo(!EXAM_URL! | findstr /c:"?" >nul && set "SEP=&"
set "EXAM_URL=!EXAM_URL!!SEP!%~1=%~2"
exit /b 0

:write_exit_server
> "%SERVER_PS1%" echo param([int]$Port, [string]$Token, [string]$Signal)
>> "%SERVER_PS1%" echo $ErrorActionPreference = 'SilentlyContinue'
>> "%SERVER_PS1%" echo $dir = Split-Path -Parent $Signal
>> "%SERVER_PS1%" echo if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir ^| Out-Null }
>> "%SERVER_PS1%" echo $listener = [System.Net.HttpListener]::new()
>> "%SERVER_PS1%" echo $listener.Prefixes.Add("http://127.0.0.1:$Port/")
>> "%SERVER_PS1%" echo $listener.Start()
>> "%SERVER_PS1%" echo while ($listener.IsListening) {
>> "%SERVER_PS1%" echo   $ctx = $listener.GetContext()
>> "%SERVER_PS1%" echo   $ctx.Response.Headers.Add('Access-Control-Allow-Origin','*')
>> "%SERVER_PS1%" echo   $ctx.Response.Headers.Add('Access-Control-Allow-Methods','GET,OPTIONS')
>> "%SERVER_PS1%" echo   if ($ctx.Request.HttpMethod -eq 'OPTIONS') { $ctx.Response.StatusCode = 204; $ctx.Response.Close(); continue }
>> "%SERVER_PS1%" echo   $ok = ($ctx.Request.Url.AbsolutePath -eq '/exit' -and $ctx.Request.QueryString['token'] -eq $Token)
>> "%SERVER_PS1%" echo   if ($ok) { Set-Content -Path $Signal -Value 'exit' -Encoding ASCII }
>> "%SERVER_PS1%" echo   $text = if ($ok) { 'OK' } else { 'DENIED' }
>> "%SERVER_PS1%" echo   $bytes = [Text.Encoding]::UTF8.GetBytes($text)
>> "%SERVER_PS1%" echo   $ctx.Response.OutputStream.Write($bytes, 0, $bytes.Length)
>> "%SERVER_PS1%" echo   $ctx.Response.Close()
>> "%SERVER_PS1%" echo   if ($ok) { break }
>> "%SERVER_PS1%" echo }
>> "%SERVER_PS1%" echo $listener.Stop()
exit /b 0
