From f23e85f3486ae3ee8d4445b808ea7b08ec1a1cdf Mon Sep 17 00:00:00 2001 From: lamtruong28 Date: Sun, 15 Nov 2026 12:47:38 +0700 Subject: [PATCH] Test and update scripts on mini pc --- .env.template | 8 +- scripts/install.bat | 181 +++++++++++++++++++++++++++++++++++------- scripts/setup.bat | 85 ++++++++++++++++++-- scripts/uninstall.bat | 139 +++++++++++++++++++++++++++----- scripts/update.bat | 151 +++++++++++++++++++++++------------ 5 files changed, 452 insertions(+), 112 deletions(-) diff --git a/.env.template b/.env.template index e465f9a..772843e 100644 --- a/.env.template +++ b/.env.template @@ -1,11 +1,11 @@ # Frontend environments -VITE_PORT = -VITE_API_BASE_URL = -VITE_API_WS_URL = +VITE_PORT = 3000 +VITE_API_BASE_URL = /api/v1/ +VITE_API_WS_URL = /ws/ VITE_SECURITY_CODE = # Backend environments -DEBUG = +DEBUG = False SECRET_KEY = ALLOWED_HOSTS = PER_PAGE_SIZE = diff --git a/scripts/install.bat b/scripts/install.bat index cdfe170..9267036 100644 --- a/scripts/install.bat +++ b/scripts/install.bat @@ -2,15 +2,27 @@ setlocal EnableDelayedExpansion :: ============================================================================ -:: CONFIGURATION (RESOLVE PARENT ROOT DIRECTORY FROM /scripts) +:: CONFIGURATION (EDIT THESE VARIABLES DIRECTLY) :: ============================================================================ set "SCRIPT_DIR=%~dp0" for %%I in ("%SCRIPT_DIR%..") do set "ROOT_DIR=%%~fI\" +set "CLEAN_ROOT=%ROOT_DIR:~0,-1%" +:: WSL2 & Docker Engine Settings set "WSL_DISTRO=Ubuntu-22.04" +set "WSL_USER=dtsadmin" +set "DOCKER_VERSION=5:28.3.2-1~ubuntu.22.04~jammy" + +:: Project & Health-Check Polling Settings +set "PROJECT_NAME=walmart" set "PROJECT_DIR=/opt/walmart" set "REGISTRY_URL=gitea.digitoolsolutions.synology.me" +set "HEALTH_PORT=3000" +set "HEALTH_PATH=/api/v1/system/health-check/" +set "HEALTH_INTERVAL=30" +set "HEALTH_MAX_RETRIES=10" +:: Windows Kiosk & Edge Settings set "DEFAULT_KIOSK_USER=Torque Vault" set "KIOSK_APP_DIR=C:\KioskApp" set "KIOSK_DATA_DIR=C:\KioskBrowserData" @@ -68,6 +80,9 @@ if not exist "%ROOT_DIR%.env" ( exit /b 1 ) +:: Restrict setup directory permissions to Administrators and SYSTEM to protect .env +icacls "%CLEAN_ROOT%" /inheritance:r /grant:r "Administrators:(OI)(CI)F" "SYSTEM:(OI)(CI)F" >nul 2>&1 + ping -n 1 8.8.8.8 >nul 2>&1 if %errorLevel% neq 0 ( echo [ERROR] No Internet connection detected! Connect LAN/Wi-Fi and run again. @@ -75,7 +90,10 @@ if %errorLevel% neq 0 ( exit /b 1 ) -powershell -NoProfile -Command "$cs = Get-CimInstance Win32_ComputerSystem; $cpu = Get-CimInstance Win32_Processor | Select-Object -First 1; if ($cs.HypervisorPresent -or $cpu.VirtualizationFirmwareEnabled) { exit 0 } else { exit 1 }" +powershell -NoProfile -Command ^ + "$cs = Get-CimInstance Win32_ComputerSystem;" ^ + "$cpu = Get-CimInstance Win32_Processor | Select-Object -First 1;" ^ + "if ($cs.HypervisorPresent -or $cpu.VirtualizationFirmwareEnabled) { exit 0 } else { exit 1 }" if %errorLevel% neq 0 ( echo [ERROR] Hardware Virtualization is DISABLED in BIOS! echo Please reboot into BIOS, enable Virtualization, and run again. @@ -118,31 +136,59 @@ if %errorLevel% neq 0 ( ) :: ============================================================================ -:: PHASE 2: INITIALIZE UBUNTU USER & ENABLE SYSTEMD IN WSL2 +:: PHASE 2: INITIALIZE UBUNTU USER, SYSTEMD & VMIDLETIMEOUT IN WSL2 :: ============================================================================ -echo [1/7] Initializing Ubuntu-22.04 and enabling systemd... -wsl -d %WSL_DISTRO% -u root bash -c "id -u dtsadmin >/dev/null 2>&1 || (useradd -m -s /bin/bash -G sudo dtsadmin && echo 'dtsadmin ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/dtsadmin)" -wsl -d %WSL_DISTRO% -u root bash -c "echo [user] > /etc/wsl.conf && echo default=dtsadmin >> /etc/wsl.conf && echo [boot] >> /etc/wsl.conf && echo systemd=true >> /etc/wsl.conf" +echo [1/7] Initializing %WSL_DISTRO%, enabling systemd and disabling VM idle timeout... +powershell -NoProfile -ExecutionPolicy Bypass -Command ^ + "$wslCfg = Join-Path $env:USERPROFILE '.wslconfig';" ^ + "Set-Content -Path $wslCfg -Value \"[wsl2]`r`nvmIdleTimeout=-1\" -Encoding Ascii" + +wsl -d %WSL_DISTRO% -u root bash -c ^ + "id -u %WSL_USER% >/dev/null 2>&1 || (useradd -m -s /bin/bash -G sudo %WSL_USER% && echo '%WSL_USER% ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/%WSL_USER%)" +wsl -d %WSL_DISTRO% -u root bash -c ^ + "printf '[user]\ndefault=%WSL_USER%\n[boot]\nsystemd=true\n' > /etc/wsl.conf" wsl --terminate %WSL_DISTRO% >nul 2>&1 timeout /t 2 /nobreak >nul :: ============================================================================ -:: PHASE 3: INSTALL & PIN DOCKER ENGINE 28.3.2 + COMPOSE V2 (IDEMPOTENT) +:: PHASE 3: INSTALL & PIN DOCKER ENGINE + COMPOSE V2 (DIRECT .SH + DYNAMIC PARAMS) :: ============================================================================ -echo [2/7] Installing Docker Engine 28.3.2 + Compose V2 (if not installed)... -wsl -d %WSL_DISTRO% -u root bash -c "echo c2V0IC1lCmlmICEgY29tbWFuZCAtdiBkb2NrZXIgPi9kZXYvbnVsbCAyPiYxOyB0aGVuCiAgYXB0LWdldCB1cGRhdGUKICBhcHQtZ2V0IGluc3RhbGwgLXkgY2EtY2VydGlmaWNhdGVzIGN1cmwgZ251cGcgbHNiLXJlbGVhc2UKICBpbnN0YWxsIC1tIDA3NTUgLWQgL2V0Yy9hcHQva2V5cmluZ3MKICBjdXJsIC1mc1NMIGh0dHBzOi8vZG93bmxvYWQuZG9ja2VyLmNvbS9saW51eC91YnVudHUvZ3BnIHwgZ3BnIC0tZGVhcm1vciAtLXllcyAtbyAvZXRjL2FwdC9rZXlyaW5ncy9kb2NrZXIuZ3BnCiAgZWNobyAiZGViIFthcmNoPSQoZHBrZyAtLXByaW50LWFyY2hpdGVjdHVyZSkgc2lnbmVkLWJ5PS9ldGMvYXB0L2tleXJpbmdzL2RvY2tlci5ncGddIGh0dHBzOi8vZG93bmxvYWQuZG9ja2VyLmNvbS9saW51eC91YnVudHUgJChsc2JfcmVsZWFzZSAtY3MpIHN0YWJsZSIgPiAvZXRjL2FwdC9zb3VyY2VzLmxpc3QuZC9kb2NrZXIubGlzdAogIGFwdC1nZXQgdXBkYXRlCiAgYXB0LWdldCBpbnN0YWxsIC15IGRvY2tlci1jZT01OjI4LjMuMi0xfnVidW50dS4yMi4wNH5qYW1teSBkb2NrZXItY2UtY2xpPTU6MjguMy4yLTF+dWJ1bnR1LjIyLjA0fmphbW15IGNvbnRhaW5lcmQuaW8gZG9ja2VyLWNvbXBvc2UtcGx1Z2luCiAgYXB0LW1hcmsgaG9sZCBkb2NrZXItY2UgZG9ja2VyLWNlLWNsaSBjb250YWluZXJkLmlvCmZpCnN5c3RlbWN0bCBlbmFibGUgZG9ja2VyCnN5c3RlbWN0bCBzdGFydCBkb2NrZXIKdXNlcm1vZCAtYUcgZG9ja2VyIGR0c2FkbWluCg== | base64 -d | bash" +echo [2/7] Installing Docker Engine (%DOCKER_VERSION%) + Compose V2... -if %errorLevel% neq 0 ( +set "STEP2_SH=%TEMP%\dts_step2.sh" +> "%STEP2_SH%" echo set -e +>> "%STEP2_SH%" echo DOCKER_VER="$1" +>> "%STEP2_SH%" echo WSL_USR="$2" +>> "%STEP2_SH%" echo if ! command -v docker ^>/dev/null 2^>^&1; then +>> "%STEP2_SH%" echo apt-get update +>> "%STEP2_SH%" echo apt-get install -y ca-certificates curl gnupg lsb-release +>> "%STEP2_SH%" echo install -m 0755 -d /etc/apt/keyrings /etc/apt/sources.list.d +>> "%STEP2_SH%" echo curl -fsSL https://download.docker.com/linux/ubuntu/gpg ^| gpg --dearmor --yes -o /etc/apt/keyrings/docker.gpg +>> "%STEP2_SH%" echo echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" ^> /etc/apt/sources.list.d/docker.list +>> "%STEP2_SH%" echo apt-get update +>> "%STEP2_SH%" echo apt-get install -y docker-ce="$DOCKER_VER" docker-ce-cli="$DOCKER_VER" containerd.io docker-compose-plugin +>> "%STEP2_SH%" echo apt-mark hold docker-ce docker-ce-cli containerd.io +>> "%STEP2_SH%" echo fi +>> "%STEP2_SH%" echo systemctl enable docker +>> "%STEP2_SH%" echo systemctl start docker +>> "%STEP2_SH%" echo usermod -aG docker "$WSL_USR" + +for /f "delims=" %%i in ('wsl -d %WSL_DISTRO% -u root wslpath -a "%STEP2_SH%"') do set "WSL_STEP2_SH=%%i" +wsl -d %WSL_DISTRO% -u root bash -c "tr -d '\r' < '%WSL_STEP2_SH%' > /tmp/dts_step2.sh && bash /tmp/dts_step2.sh '%DOCKER_VERSION%' '%WSL_USER%'; RC=$?; rm -f /tmp/dts_step2.sh; exit $RC" +set "STEP2_ERR=%errorLevel%" +del /f /q "%STEP2_SH%" >nul 2>&1 + +if %STEP2_ERR% neq 0 ( echo [ERROR] Docker installation or startup failed inside WSL. pause exit /b 1 ) :: ============================================================================ -:: PHASE 4: DEPLOY DOCKER CONTAINERS & REGISTER WSL BOOT TASK +:: PHASE 4: DEPLOY CONTAINERS & VERIFY ONLINE (ONE CONTINUOUS WSL SESSION) :: ============================================================================ -echo [3/7] Deploying Walmart containers to %PROJECT_DIR%... +echo [3/7] Deploying Walmart containers and waiting for Online status in %PROJECT_DIR%... echo Please log in to Docker registry (%REGISTRY_URL%) if prompted: wsl -d %WSL_DISTRO% -u root docker login %REGISTRY_URL% if %errorLevel% neq 0 ( @@ -151,19 +197,47 @@ if %errorLevel% neq 0 ( exit /b 1 ) -set "CLEAN_ROOT=%ROOT_DIR:~0,-1%" for /f "delims=" %%i in ('wsl -d %WSL_DISTRO% -u root wslpath -a "%CLEAN_ROOT%"') do set "WSL_ROOT_DIR=%%i" -wsl -d %WSL_DISTRO% -u root bash -c "mkdir -p %PROJECT_DIR% && cp '%WSL_ROOT_DIR%/compose.yml' %PROJECT_DIR%/ && cp '%WSL_ROOT_DIR%/.env' %PROJECT_DIR%/ && sed -i 's/\r$//' %PROJECT_DIR%/.env && cd %PROJECT_DIR% && docker compose pull && docker compose up -d" -if %errorLevel% neq 0 ( - echo [ERROR] Failed to start Docker containers. +set "STEP3_SH=%TEMP%\dts_step3.sh" +> "%STEP3_SH%" echo set -e +>> "%STEP3_SH%" echo SRC_DIR="$1" +>> "%STEP3_SH%" echo PROJ_DIR="$2" +>> "%STEP3_SH%" echo PROJ_NAME="$3" +>> "%STEP3_SH%" echo PORT="$4" +>> "%STEP3_SH%" echo ENDPOINT="$5" +>> "%STEP3_SH%" echo INTERVAL="$6" +>> "%STEP3_SH%" echo MAX_RETRIES="$7" +>> "%STEP3_SH%" echo mkdir -p "$PROJ_DIR" +>> "%STEP3_SH%" echo cp "$SRC_DIR/compose.yml" "$PROJ_DIR/compose.yml" +>> "%STEP3_SH%" echo tr -d '\r' ^< "$SRC_DIR/.env" ^> "$PROJ_DIR/.env" +>> "%STEP3_SH%" echo cd "$PROJ_DIR" +>> "%STEP3_SH%" echo docker compose -p "$PROJ_NAME" pull +>> "%STEP3_SH%" echo docker compose -p "$PROJ_NAME" up -d +>> "%STEP3_SH%" echo echo " - Up complete. Polling http://localhost:${PORT}${ENDPOINT} every ${INTERVAL}s (max ${MAX_RETRIES} attempts)..." +>> "%STEP3_SH%" echo for i in $(seq 1 "$MAX_RETRIES"); do +>> "%STEP3_SH%" echo RES=$(curl -kfsS --max-time 3 "http://localhost:${PORT}${ENDPOINT}" 2^>/dev/null ^|^| true) +>> "%STEP3_SH%" echo if echo "$RES" ^| grep -qi "Online"; then +>> "%STEP3_SH%" echo echo " - Server is Online and migrations are complete!" +>> "%STEP3_SH%" echo exit 0 +>> "%STEP3_SH%" echo fi +>> "%STEP3_SH%" echo echo " - Attempt $i/$MAX_RETRIES: Server is still initializing/migrating, retrying in ${INTERVAL}s..." +>> "%STEP3_SH%" echo sleep "$INTERVAL" +>> "%STEP3_SH%" echo done +>> "%STEP3_SH%" echo echo " - [ERROR] Timed out waiting for Server on port $PORT to become Online!" +>> "%STEP3_SH%" echo exit 1 + +for /f "delims=" %%i in ('wsl -d %WSL_DISTRO% -u root wslpath -a "%STEP3_SH%"') do set "WSL_STEP3_SH=%%i" +wsl -d %WSL_DISTRO% -u root bash -c "tr -d '\r' < '%WSL_STEP3_SH%' > /tmp/dts_step3.sh && bash /tmp/dts_step3.sh '%WSL_ROOT_DIR%' '%PROJECT_DIR%' '%PROJECT_NAME%' '%HEALTH_PORT%' '%HEALTH_PATH%' '%HEALTH_INTERVAL%' '%HEALTH_MAX_RETRIES%'; RC=$?; rm -f /tmp/dts_step3.sh; exit $RC" +set "STEP3_ERR=%errorLevel%" +del /f /q "%STEP3_SH%" >nul 2>&1 + +if %STEP3_ERR% neq 0 ( + echo [ERROR] Deployment or server health-check failed. Check logs with: wsl -d %WSL_DISTRO% -u root docker logs tv-backend-prod pause exit /b 1 ) -echo [4/7] Configuring WSL + Docker to auto-start on Windows Boot... -powershell -NoProfile -ExecutionPolicy Bypass -Command "$action = New-ScheduledTaskAction -Execute 'wsl.exe' -Argument '-d %WSL_DISTRO% -u root -- service docker start'; $trigger = New-ScheduledTaskTrigger -AtStartup; $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest; $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit 0; Register-ScheduledTask -TaskName 'DTS_WSL_Docker_AutoStart' -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null" - :: ============================================================================ :: PHASE 5: INTERACTIVE KIOSK USER CREATION & AUTO-LOGON SETUP :: ============================================================================ @@ -197,19 +271,40 @@ if /i "%PREV_KIOSK_USER%"=="Administrator" goto :SKIP_REMOVE_OLD echo - Removing previous Kiosk user "%PREV_KIOSK_USER%" and its profile... for /f "tokens=3" %%S in ('query user "%PREV_KIOSK_USER%" 2^>nul ^| findstr /i "%PREV_KIOSK_USER%"') do logoff %%S >nul 2>&1 timeout /t 2 /nobreak >nul -powershell -NoProfile -ExecutionPolicy Bypass -Command "$u='%PREV_KIOSK_USER%'; $acc=Get-LocalUser -Name $u -ErrorAction SilentlyContinue; if ($acc) { $sid=$acc.SID.Value; Get-CimInstance Win32_UserProfile -Filter \"SID='$sid'\" -ErrorAction SilentlyContinue | Remove-CimInstance -ErrorAction SilentlyContinue; Remove-LocalUser -Name $u -ErrorAction SilentlyContinue }" +powershell -NoProfile -ExecutionPolicy Bypass -Command ^ + "$u='%PREV_KIOSK_USER%';" ^ + "$acc=Get-LocalUser -Name $u -ErrorAction SilentlyContinue;" ^ + "if ($acc) {" ^ + " $sid=$acc.SID.Value;" ^ + " Get-CimInstance Win32_UserProfile -Filter \"SID='$sid'\" -ErrorAction SilentlyContinue | Remove-CimInstance -ErrorAction SilentlyContinue;" ^ + " Remove-LocalUser -Name $u -ErrorAction SilentlyContinue" ^ + "}" :SKIP_REMOVE_OLD net accounts /minpwlen:0 >nul 2>&1 -powershell -NoProfile -ExecutionPolicy Bypass -Command "$u = '%KIOSK_USER%'; $p = '%KIOSK_PASS%'; $existing = Get-LocalUser -Name $u -ErrorAction SilentlyContinue; if (-not $existing) { if ([string]::IsNullOrEmpty($p)) { New-LocalUser -Name $u -NoPassword | Out-Null } else { New-LocalUser -Name $u -Password (ConvertTo-SecureString $p -AsPlainText -Force) -PasswordNeverExpires | Out-Null } Add-LocalGroupMember -Group 'Users' -Member $u -ErrorAction SilentlyContinue } else { Enable-LocalUser -Name $u | Out-Null; if ([string]::IsNullOrEmpty($p)) { Set-LocalUser -Name $u -Password ([securestring]::new()) } else { Set-LocalUser -Name $u -Password (ConvertTo-SecureString $p -AsPlainText -Force) -PasswordNeverExpires $true } }" -wmic useraccount where name="%KIOSK_USER%" set PasswordExpires=False >nul 2>&1 -net user "%KIOSK_USER%" /logonpasswordchg:no >nul 2>&1 +powershell -NoProfile -ExecutionPolicy Bypass -Command ^ + "$u = '%KIOSK_USER%';" ^ + "$p = '%KIOSK_PASS%';" ^ + "$existing = Get-LocalUser -Name $u -ErrorAction SilentlyContinue;" ^ + "if (-not $existing) {" ^ + " if ([string]::IsNullOrEmpty($p)) { New-LocalUser -Name $u -NoPassword | Out-Null }" ^ + " else { New-LocalUser -Name $u -Password (ConvertTo-SecureString $p -AsPlainText -Force) -PasswordNeverExpires | Out-Null }" ^ + " Add-LocalGroupMember -Group 'Users' -Member $u -ErrorAction SilentlyContinue" ^ + "} else {" ^ + " Enable-LocalUser -Name $u | Out-Null;" ^ + " if ([string]::IsNullOrEmpty($p)) { Set-LocalUser -Name $u -Password ([securestring]::new()) }" ^ + " else { Set-LocalUser -Name $u -Password (ConvertTo-SecureString $p -AsPlainText -Force) -PasswordNeverExpires $true }" ^ + "}" + if %errorLevel% neq 0 ( echo [ERROR] Failed to create or update user "%KIOSK_USER%". pause exit /b 1 ) +wmic useraccount where name="%KIOSK_USER%" set PasswordExpires=False >nul 2>&1 +net user "%KIOSK_USER%" /logonpasswordchg:no >nul 2>&1 + echo [6/7] Applying Kiosk Shell, Auto-Logon and Persistent Browser Profile... if not exist "%KIOSK_DATA_DIR%" mkdir "%KIOSK_DATA_DIR%" if not exist "%KIOSK_APP_DIR%" mkdir "%KIOSK_APP_DIR%" @@ -231,7 +326,36 @@ reg add "%EDGE_POL%" /v "InPrivateModeAvailability" /t REG_DWORD /d 1 /f >nul reg add "%EDGE_POL%" /v "ClearBrowsingDataOnExit" /t REG_DWORD /d 0 /f >nul reg add "%EDGE_POL%" /v "RestoreOnStartup" /t REG_DWORD /d 4 /f >nul -powershell -NoProfile -ExecutionPolicy Bypass -Command "$user = '%KIOSK_USER%'; $edge = '%EDGE_EXE%'; $sid = (New-Object System.Security.Principal.NTAccount($user)).Translate([System.Security.Principal.SecurityIdentifier]).Value; $profReg = \"HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$sid\"; if (-not (Test-Path $profReg)) { Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; using System.Text; public class Prof { [DllImport(\"userenv.dll\", CharSet=CharSet.Unicode, SetLastError=true)] public static extern bool CreateProfile(string pszUserSid, string pszUserName, StringBuilder pszProfilePath, uint cchProfilePath); }'; $sb = New-Object System.Text.StringBuilder 260; [Prof]::CreateProfile($sid, $user, $sb, $sb.Capacity) | Out-Null } $profilePath = (Get-ItemProperty $profReg -ErrorAction SilentlyContinue).ProfileImagePath; if ($profilePath) { $hivePath = Join-Path $profilePath 'NTUSER.DAT'; $edgeCmd = '\"' + $edge + '\" --kiosk \"file:///C:/KioskApp/startup.html\" --edge-kiosk-type=fullscreen --user-data-dir=\"C:\KioskBrowserData\" --no-first-run --disable-features=TranslateUI --allow-file-access-from-files'; $loaded = $false; if (-not (Test-Path \"Registry::HKEY_USERS\$sid\")) { reg load \"HKU\$sid\" \"$hivePath\" >$null 2>&1; if ($LASTEXITCODE -eq 0) { $loaded = $true } } if (Test-Path \"Registry::HKEY_USERS\$sid\") { [Microsoft.Win32.Registry]::SetValue(\"HKEY_USERS\$sid\Software\Microsoft\Windows\CurrentVersion\Policies\System\", 'Shell', $edgeCmd, [Microsoft.Win32.RegistryValueKind]::String); $stuckPath = \"Registry::HKEY_USERS\$sid\Software\Microsoft\Windows\CurrentVersion\Explorer\StuckRects3\"; if (Test-Path $stuckPath) { $v = (Get-ItemProperty -Path $stuckPath -Name Settings).Settings; $v[8] = 3; Set-ItemProperty -Path $stuckPath -Name Settings -Value $v } } if ($loaded) { [gc]::Collect(); Start-Sleep -Milliseconds 300; reg unload \"HKU\$sid\" >$null 2>&1 } }" +powershell -NoProfile -ExecutionPolicy Bypass -Command ^ + "$user = '%KIOSK_USER%';" ^ + "$edge = '%EDGE_EXE%';" ^ + "$sid = (New-Object System.Security.Principal.NTAccount($user)).Translate([System.Security.Principal.SecurityIdentifier]).Value;" ^ + "$profReg = \"HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$sid\";" ^ + "if (-not (Test-Path $profReg)) {" ^ + " Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; using System.Text; public class Prof { [DllImport(\"userenv.dll\", CharSet=CharSet.Unicode, SetLastError=true)] public static extern bool CreateProfile(string pszUserSid, string pszUserName, StringBuilder pszProfilePath, uint cchProfilePath); }';" ^ + " $sb = New-Object System.Text.StringBuilder 260;" ^ + " [Prof]::CreateProfile($sid, $user, $sb, $sb.Capacity) | Out-Null" ^ + "}" ^ + "$profilePath = (Get-ItemProperty $profReg -ErrorAction SilentlyContinue).ProfileImagePath;" ^ + "if ($profilePath) {" ^ + " $hivePath = Join-Path $profilePath 'NTUSER.DAT';" ^ + " $edgeCmd = '\"' + $edge + '\" --kiosk \"file:///C:/KioskApp/startup.html\" --edge-kiosk-type=fullscreen --user-data-dir=\"C:\KioskBrowserData\" --no-first-run --disable-features=TranslateUI --allow-file-access-from-files';" ^ + " $loaded = $false;" ^ + " if (-not (Test-Path \"Registry::HKEY_USERS\$sid\")) {" ^ + " reg load \"HKU\$sid\" \"$hivePath\" >$null 2>&1;" ^ + " if ($LASTEXITCODE -eq 0) { $loaded = $true }" ^ + " }" ^ + " if (Test-Path \"Registry::HKEY_USERS\$sid\") {" ^ + " [Microsoft.Win32.Registry]::SetValue(\"HKEY_USERS\$sid\Software\Microsoft\Windows\CurrentVersion\Policies\System\", 'Shell', $edgeCmd, [Microsoft.Win32.RegistryValueKind]::String);" ^ + " $stuckPath = \"Registry::HKEY_USERS\$sid\Software\Microsoft\Windows\CurrentVersion\Explorer\StuckRects3\";" ^ + " if (Test-Path $stuckPath) {" ^ + " $v = (Get-ItemProperty -Path $stuckPath -Name Settings).Settings;" ^ + " $v[8] = 3;" ^ + " Set-ItemProperty -Path $stuckPath -Name Settings -Value $v" ^ + " }" ^ + " }" ^ + " if ($loaded) { [gc]::Collect(); Start-Sleep -Milliseconds 300; reg unload \"HKU\$sid\" >$null 2>&1 }" ^ + "}" schtasks /delete /tn "DTS_Torque_Vault_Kiosk" /f >nul 2>&1 @@ -261,12 +385,13 @@ reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" /v "AUOption echo. echo ============================================================================ echo ALL-IN-ONE 24/7 KIOSK DEPLOYMENT COMPLETED! -echo - WSL2 + Docker 28.3.2 : Installed and Auto-Starting at Boot -echo - Walmart Containers : Running in %PROJECT_DIR% -echo - Kiosk User : %KIOSK_USER% (Auto-Logon + Persistent Data) -echo - Power and Updates : 24/7 Always-On (No Sleep / No Auto-Reboot) +echo - WSL2 + Docker : %DOCKER_VERSION% (Auto-Starting at Boot) +echo - Walmart Containers : Online and Verified on Port %HEALTH_PORT% in %PROJECT_DIR% +echo - Kiosk User : %KIOSK_USER% (Auto-Logon + Persistent Data) +echo - Power and Updates : 24/7 Always-On (No Sleep / No Auto-Reboot) echo ============================================================================ echo. +set "REBOOT_FINAL=" set /p REBOOT_FINAL="Reboot now to enter full Kiosk Production mode? (Y/N): " if /i "%REBOOT_FINAL%"=="Y" shutdown /r /t 3 pause \ No newline at end of file diff --git a/scripts/setup.bat b/scripts/setup.bat index 24cad71..1a6d035 100644 --- a/scripts/setup.bat +++ b/scripts/setup.bat @@ -1,5 +1,5 @@ @echo off -setlocal +setlocal EnableDelayedExpansion :: ============================================================================ :: CONFIGURATION @@ -7,9 +7,10 @@ setlocal set "GITEA_URL=https://gitea.digitoolsolutions.synology.me" set "REPO_OWNER=lamtruong28" set "REPO_NAME=mini-pc-setup" +set "EXTRACT_DIR=%USERPROFILE%\Apps\%REPO_NAME%" :: ============================================================================ -:: AUTO-ELEVATE TO ADMINISTRATOR +:: 0. AUTO-ELEVATE TO ADMINISTRATOR :: ============================================================================ net session >nul 2>&1 if %errorLevel% neq 0 ( @@ -24,11 +25,81 @@ echo =========================================================================== echo Repository : %GITEA_URL%/%REPO_OWNER%/%REPO_NAME% echo. -powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='Stop'; $base='%GITEA_URL%'.TrimEnd('/'); $owner='%REPO_OWNER%'; $repo='%REPO_NAME%'; $apiUrl=\"$base/api/v1/repos/$owner/$repo/releases/latest\"; $cred=$null; try { $rel=Invoke-RestMethod -Uri $apiUrl -UseBasicParsing } catch { Write-Host '[AUTH] Private repository detected. Please sign in to Gitea:' -ForegroundColor Yellow; $cred=Get-Credential -Message 'Enter Gitea Credentials'; $rel=Invoke-RestMethod -Uri $apiUrl -Credential $cred -UseBasicParsing }; $tag=$rel.tag_name; $rawUrl=\"$base/$owner/$repo/raw/tag/$tag/scripts/bootstrap.ps1\"; if ($null -ne $cred) { $script=Invoke-RestMethod -Uri $rawUrl -Credential $cred -UseBasicParsing } else { $script=Invoke-RestMethod -Uri $rawUrl -UseBasicParsing }; & ([scriptblock]::Create($script)) -GiteaUrl $base -Owner $owner -Repo $repo -ReleaseJson $rel -Credential $cred" - +:: ============================================================================ +:: 1. PRE-CHECK DNS & INTERNET CONNECTIVITY +:: ============================================================================ +echo [1/3] Checking network and DNS resolution for %GITEA_URL%... +powershell -NoProfile -ExecutionPolicy Bypass -Command ^ + "$hostName = ([System.Uri]'%GITEA_URL%').Host;" ^ + "try { [System.Net.Dns]::GetHostAddresses($hostName) | Out-Null; exit 0 }" ^ + "catch { Write-Host '[ERROR] Cannot resolve DNS for' $hostName '- Check Internet.' -ForegroundColor Red; exit 1 }" if %errorLevel% neq 0 ( - echo. - echo [ERROR] Bootstrap failed. Verify that at least one Release exists on Gitea. pause exit /b 1 -) \ No newline at end of file +) + +:: ============================================================================ +:: 2. FETCH LATEST RELEASE (PUBLIC FIRST, AUTH ONLY ON HTTP 401/403/404) +:: ============================================================================ +echo [2/3] Fetching latest release package... +set "ZIP_FILE=%TEMP%\%REPO_NAME%-latest.zip" +if exist "%ZIP_FILE%" del /f /q "%ZIP_FILE%" >nul 2>&1 + +powershell -NoProfile -ExecutionPolicy Bypass -Command ^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;" ^ + "$apiUrl = '%GITEA_URL%/api/v1/repos/%REPO_OWNER%/%REPO_NAME%/releases/latest';" ^ + "$outZip = '%ZIP_FILE%';" ^ + "$headers = @{ 'User-Agent' = 'DTS-Bootstrapper' };" ^ + "$needAuth = $false;" ^ + "try {" ^ + " $rel = Invoke-RestMethod -Uri $apiUrl -Headers $headers -ErrorAction Stop;" ^ + "} catch {" ^ + " $status = $null;" ^ + " if ($_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode }" ^ + " if ($status -in @(401, 403, 404)) { $needAuth = $true }" ^ + " else { Write-Host ('[ERROR] Network/SSL error connecting to Gitea: ' + $_.Exception.Message) -ForegroundColor Red; exit 1 }" ^ + "}" ^ + "if ($needAuth) {" ^ + " Write-Host '[AUTH] Private repository or restricted release. Please sign in to Gitea:';" ^ + " $cred = Get-Credential -UserName '%REPO_OWNER%' -Message 'Enter Gitea credentials';" ^ + " if (-not $cred) { exit 1 }" ^ + " $pair = '{0}:{1}' -f $cred.UserName, $cred.GetNetworkCredential().Password;" ^ + " $headers['Authorization'] = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($pair));" ^ + " try { $rel = Invoke-RestMethod -Uri $apiUrl -Headers $headers -ErrorAction Stop }" ^ + " catch { Write-Host ('[ERROR] Gitea authentication or release lookup failed: ' + $_.Exception.Message) -ForegroundColor Red; exit 1 }" ^ + "}" ^ + "$zipUrl = $rel.zipball_url;" ^ + "if (-not $zipUrl) { Write-Host '[ERROR] No release zipball found. Ensure at least one Release is published on Gitea.' -ForegroundColor Red; exit 1 }" ^ + "Write-Host (' - Downloading release ' + $rel.tag_name + '...');" ^ + "Invoke-WebRequest -Uri $zipUrl -Headers $headers -OutFile $outZip -UseBasicParsing -ErrorAction Stop" + +if %errorLevel% neq 0 ( + echo [ERROR] Bootstrap failed. + pause + exit /b 1 +) + +:: ============================================================================ +:: 3. EXTRACT & LAUNCH INSTALLER +:: ============================================================================ +echo [3/3] Extracting to %EXTRACT_DIR% and launching install.bat... +if exist "%EXTRACT_DIR%" rmdir /s /q "%EXTRACT_DIR%" >nul 2>&1 +mkdir "%EXTRACT_DIR%" >nul 2>&1 + +powershell -NoProfile -ExecutionPolicy Bypass -Command ^ + "$tmpExtract = Join-Path $env:TEMP 'dts_release_extract';" ^ + "if (Test-Path $tmpExtract) { Remove-Item $tmpExtract -Recurse -Force }" ^ + "Expand-Archive -Path '%ZIP_FILE%' -DestinationPath $tmpExtract -Force;" ^ + "$inner = Get-ChildItem -Path $tmpExtract -Directory | Select-Object -First 1;" ^ + "if ($inner) { Copy-Item -Path (Join-Path $inner.FullName '*') -Destination '%EXTRACT_DIR%' -Recurse -Force }" ^ + "else { Copy-Item -Path (Join-Path $tmpExtract '*') -Destination '%EXTRACT_DIR%' -Recurse -Force }" ^ + "Remove-Item $tmpExtract -Recurse -Force;" ^ + "Remove-Item '%ZIP_FILE%' -Force" + +if not exist "%EXTRACT_DIR%\scripts\install.bat" ( + echo [ERROR] scripts\install.bat not found inside the extracted release! + pause + exit /b 1 +) + +call "%EXTRACT_DIR%\scripts\install.bat" \ No newline at end of file diff --git a/scripts/uninstall.bat b/scripts/uninstall.bat index 83b2318..e238596 100644 --- a/scripts/uninstall.bat +++ b/scripts/uninstall.bat @@ -2,9 +2,17 @@ setlocal EnableDelayedExpansion :: ============================================================================ -:: CONFIGURATION +:: CONFIGURATION (SYNCED WITH INSTALL.BAT) :: ============================================================================ +set "SCRIPT_DIR=%~dp0" +for %%I in ("%SCRIPT_DIR%..") do ( + set "ROOT_DIR=%%~fI\" + set "ROOT_FOLDER_NAME=%%~nxI" +) +set "CLEAN_ROOT=%ROOT_DIR:~0,-1%" + set "WSL_DISTRO=Ubuntu-22.04" +set "PROJECT_NAME=walmart" set "PROJECT_DIR=/opt/walmart" set "KIOSK_APP_DIR=C:\KioskApp" set "KIOSK_DATA_DIR=C:\KioskBrowserData" @@ -23,19 +31,41 @@ echo =========================================================================== echo DTS TORQUE VAULT - KIOSK MODE UNINSTALLER AND SYSTEM RESTORE echo ============================================================================ echo. -echo This tool will: -echo 1. Disable Windows Auto-Logon and Kiosk Shell restrictions -echo 2. Remove or restore the dedicated Kiosk user account -echo 3. Remove startup tasks and restore default Power / Update policies -echo 4. Optionally stop and remove Walmart Docker containers +echo Select uninstall mode: +echo [1] Auto Wipe All - Automatically remove Kiosk user, browser data, +echo scheduled tasks, Docker containers, database volumes +echo and the '%ROOT_FOLDER_NAME%' setup folder +echo [2] Manual / Custom - Choose step-by-step what to keep or delete +echo [0] Cancel echo. -set /p CONFIRM="Are you sure you want to uninstall Kiosk Mode? (Y/N): " -if /i not "%CONFIRM%"=="Y" ( +set "UNINSTALL_MODE=" +set /p UNINSTALL_MODE="Enter your choice [1 / 2 / 0]: " + +if "%UNINSTALL_MODE%"=="0" ( echo Uninstall cancelled. pause exit /b 0 ) +set "AUTO_WIPE=0" +if "%UNINSTALL_MODE%"=="1" ( + set "AUTO_WIPE=1" + echo. + echo [WARNING] Option 1 selected: ALL Kiosk settings, user profiles, browser data, + echo and local database volumes will be permanently wiped! + set "CONFIRM_WIPE=" + set /p CONFIRM_WIPE="Type YES to confirm full automatic wipe: " + if /i not "!CONFIRM_WIPE!"=="YES" ( + echo Uninstall cancelled. + pause + exit /b 0 + ) +) else if not "%UNINSTALL_MODE%"=="2" ( + echo [ERROR] Invalid selection. Exiting. + pause + exit /b 1 +) + :: ============================================================================ :: 1. DETECT CURRENT KIOSK ACCOUNT & DISABLE AUTO-LOGON :: ============================================================================ @@ -71,13 +101,44 @@ echo Detected Kiosk account: "%KIOSK_USER%" for /f "tokens=3" %%S in ('query user "%KIOSK_USER%" 2^>nul ^| findstr /i "%KIOSK_USER%"') do logoff %%S >nul 2>&1 timeout /t 2 /nobreak >nul -set /p DEL_USER="Delete Kiosk user account '%KIOSK_USER%' and its profile? (Y=Delete / N=Restore Desktop): " +set "DEL_USER=Y" +if "%AUTO_WIPE%"=="0" ( + set /p DEL_USER="Delete Kiosk user account '%KIOSK_USER%' and its profile? (Y=Delete / N=Restore Desktop): " +) + if /i "%DEL_USER%"=="Y" ( - powershell -NoProfile -ExecutionPolicy Bypass -Command "$u='%KIOSK_USER%'; $acc=Get-LocalUser -Name $u -ErrorAction SilentlyContinue; if ($acc) { $sid=$acc.SID.Value; Get-CimInstance Win32_UserProfile -Filter \"SID='$sid'\" -ErrorAction SilentlyContinue | Remove-CimInstance -ErrorAction SilentlyContinue; Remove-LocalUser -Name $u -ErrorAction SilentlyContinue }" + powershell -NoProfile -ExecutionPolicy Bypass -Command ^ + "$u='%KIOSK_USER%';" ^ + "$acc=Get-LocalUser -Name $u -ErrorAction SilentlyContinue;" ^ + "if ($acc) {" ^ + " $sid=$acc.SID.Value;" ^ + " Get-CimInstance Win32_UserProfile -Filter \"SID='$sid'\" -ErrorAction SilentlyContinue | Remove-CimInstance -ErrorAction SilentlyContinue;" ^ + " Remove-LocalUser -Name $u -ErrorAction SilentlyContinue" ^ + "}" echo - Removed Kiosk user "%KIOSK_USER%" and its local profile. ) else ( - powershell -NoProfile -ExecutionPolicy Bypass -Command "$u='%KIOSK_USER%'; $acc=Get-LocalUser -Name $u -ErrorAction SilentlyContinue; if ($acc) { $sid=$acc.SID.Value; $p=(Get-ItemProperty \"HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$sid\" -ErrorAction SilentlyContinue).ProfileImagePath; if ($p -and (Test-Path \"$p\NTUSER.DAT\")) { $loaded=$false; if (-not (Test-Path \"Registry::HKEY_USERS\$sid\")) { reg.exe load \"HKU\$sid\" \"$p\NTUSER.DAT\" >$null 2>&1; if ($LASTEXITCODE -eq 0) { $loaded=$true } } if (Test-Path \"Registry::HKEY_USERS\$sid\") { reg.exe delete \"HKU\$sid\Software\Microsoft\Windows\CurrentVersion\Policies\System\" /v Shell /f >$null 2>&1; reg.exe delete \"HKU\$sid\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" /v Shell /f >$null 2>&1 } if ($loaded) { [gc]::Collect(); Start-Sleep 1; reg.exe unload \"HKU\$sid\" >$null 2>&1 } } }" - echo - Restored normal Windows Desktop shell for "%KIOSK_USER%". + powershell -NoProfile -ExecutionPolicy Bypass -Command ^ + "$u='%KIOSK_USER%';" ^ + "$acc=Get-LocalUser -Name $u -ErrorAction SilentlyContinue;" ^ + "if ($acc) {" ^ + " $sid=$acc.SID.Value;" ^ + " $p=(Get-ItemProperty \"HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$sid\" -ErrorAction SilentlyContinue).ProfileImagePath;" ^ + " if ($p -and (Test-Path \"$p\NTUSER.DAT\")) {" ^ + " $loaded=$false;" ^ + " if (-not (Test-Path \"Registry::HKEY_USERS\$sid\")) {" ^ + " reg.exe load \"HKU\$sid\" \"$p\NTUSER.DAT\" >$null 2>&1;" ^ + " if ($LASTEXITCODE -eq 0) { $loaded=$true }" ^ + " }" ^ + " if (Test-Path \"Registry::HKEY_USERS\$sid\") {" ^ + " reg.exe delete \"HKU\$sid\Software\Microsoft\Windows\CurrentVersion\Policies\System\" /v Shell /f >$null 2>&1;" ^ + " reg.exe delete \"HKU\$sid\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" /v Shell /f >$null 2>&1;" ^ + " $stuckPath=\"Registry::HKEY_USERS\$sid\Software\Microsoft\Windows\CurrentVersion\Explorer\StuckRects3\";" ^ + " if (Test-Path $stuckPath) { $v=(Get-ItemProperty -Path $stuckPath -Name Settings).Settings; $v[8]=2; Set-ItemProperty -Path $stuckPath -Name Settings -Value $v }" ^ + " }" ^ + " if ($loaded) { [gc]::Collect(); Start-Sleep 1; reg.exe unload \"HKU\$sid\" >$null 2>&1 }" ^ + " }" ^ + "}" + echo - Restored normal Windows Desktop shell and taskbar for "%KIOSK_USER%". ) goto :AFTER_KIOSK_USER @@ -96,10 +157,15 @@ reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v "DTS_Mast if exist "%KIOSK_APP_DIR%" rmdir /s /q "%KIOSK_APP_DIR%" >nul 2>&1 if exist "%KIOSK_DATA_DIR%" ( - set /p DEL_BROWSER="Delete persistent Kiosk browser data at %KIOSK_DATA_DIR%? (Y/N): " + set "DEL_BROWSER=Y" + if "%AUTO_WIPE%"=="0" ( + set /p DEL_BROWSER="Delete persistent Kiosk browser data at %KIOSK_DATA_DIR%? (Y/N): " + ) if /i "!DEL_BROWSER!"=="Y" ( rmdir /s /q "%KIOSK_DATA_DIR%" >nul 2>&1 echo - Removed %KIOSK_DATA_DIR% + ) else ( + echo - Preserved %KIOSK_DATA_DIR% ) ) @@ -111,28 +177,46 @@ powercfg -setactive 381b4222-f694-41f0-9685-ff5bb260df2e >nul 2>&1 reg delete "HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" /v "NoAutoRebootWithLoggedOnUsers" /f >nul 2>&1 reg delete "HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" /v "AUOptions" /f >nul 2>&1 +if "%AUTO_WIPE%"=="1" if exist "%USERPROFILE%\.wslconfig" del /f /q "%USERPROFILE%\.wslconfig" >nul 2>&1 & echo - Removed custom .wslconfig. + :: ============================================================================ -:: 5. OPTIONAL: STOP AND REMOVE WALMART DOCKER CONTAINERS +:: 5. STOP AND REMOVE WALMART DOCKER CONTAINERS :: ============================================================================ echo [5/5] Checking WSL Docker containers... wsl -d %WSL_DISTRO% -u root true >nul 2>&1 if %errorLevel% neq 0 goto :UNINSTALL_DONE -set "STOP_DOCKER=" -set /p STOP_DOCKER="Stop and remove Walmart Docker containers in %PROJECT_DIR%? (Y/N): " +set "STOP_DOCKER=Y" +if "%AUTO_WIPE%"=="0" ( + set /p STOP_DOCKER="Stop and remove Walmart Docker containers in %PROJECT_DIR%? (Y/N): " +) if /i not "%STOP_DOCKER%"=="Y" goto :UNINSTALL_DONE -set "DEL_VOLUMES=" -set /p DEL_VOLUMES="Also delete database volumes - WARNING deletes all local data? (Y/N): " +set "DEL_VOLUMES=Y" +if "%AUTO_WIPE%"=="0" ( + set /p DEL_VOLUMES="Also delete database volumes - WARNING deletes all local data? (Y/N): " +) + if /i "%DEL_VOLUMES%"=="Y" ( - wsl -d %WSL_DISTRO% -u root bash -c "cd %PROJECT_DIR% 2>/dev/null && docker compose down -v && rm -rf %PROJECT_DIR%" - echo - Removed containers, volumes, and %PROJECT_DIR%. + wsl -d %WSL_DISTRO% -u root bash -c "cd '%PROJECT_DIR%' 2>/dev/null && docker compose -p '%PROJECT_NAME%' down -v --remove-orphans; rm -rf '%PROJECT_DIR%'" + echo - Removed containers, database volumes, and %PROJECT_DIR%. ) else ( - wsl -d %WSL_DISTRO% -u root bash -c "cd %PROJECT_DIR% 2>/dev/null && docker compose down" + wsl -d %WSL_DISTRO% -u root bash -c "cd '%PROJECT_DIR%' 2>/dev/null && docker compose -p '%PROJECT_NAME%' down --remove-orphans" echo - Stopped and removed containers - database volumes preserved. ) :UNINSTALL_DONE +set "DEL_SETUP_DIR=N" +if /i "%ROOT_FOLDER_NAME%"=="mini-pc-setup" ( + if "%AUTO_WIPE%"=="1" ( + set "DEL_SETUP_DIR=Y" + ) else ( + set /p DEL_SETUP_DIR="Delete setup folder '%CLEAN_ROOT%' only? (Y/N): " + ) +) else ( + echo [INFO] Skipping setup folder deletion because parent folder is '%ROOT_FOLDER_NAME%' - not 'mini-pc-setup'. +) + echo. echo ============================================================================ echo UNINSTALL COMPLETED! @@ -140,7 +224,20 @@ echo - Windows Auto-Logon and Kiosk restrictions have been removed echo - Normal Windows Desktop and Power/Update policies restored echo ============================================================================ echo. + set "REBOOT_NOW=" set /p REBOOT_NOW="Reboot now to apply all changes cleanly? (Y/N): " + +if /i "%DEL_SETUP_DIR%"=="Y" ( + echo Cleaning up '%CLEAN_ROOT%' in 2 seconds - other folders in parent directory remain untouched... + cd /d "%TEMP%" + if /i "%REBOOT_NOW%"=="Y" ( + start "" /b cmd /c "timeout /t 2 /nobreak >nul & rmdir /s /q "%CLEAN_ROOT%" & shutdown /r /t 2" + ) else ( + start "" /b cmd /c "timeout /t 2 /nobreak >nul & rmdir /s /q "%CLEAN_ROOT%"" + ) + exit /b 0 +) + if /i "%REBOOT_NOW%"=="Y" shutdown /r /t 3 pause \ No newline at end of file diff --git a/scripts/update.bat b/scripts/update.bat index e698bd5..bdd9a36 100644 --- a/scripts/update.bat +++ b/scripts/update.bat @@ -2,15 +2,25 @@ setlocal EnableDelayedExpansion :: ============================================================================ -:: CONFIGURATION (RESOLVE PARENT ROOT DIRECTORY FROM /scripts) +:: CONFIGURATION (SYNCED WITH INSTALL.BAT & UNINSTALL.BAT) :: ============================================================================ set "SCRIPT_DIR=%~dp0" for %%I in ("%SCRIPT_DIR%..") do set "ROOT_DIR=%%~fI\" set "CLEAN_ROOT=%ROOT_DIR:~0,-1%" +:: WSL2 & Project Settings set "WSL_DISTRO=Ubuntu-22.04" +set "PROJECT_NAME=walmart" set "PROJECT_DIR=/opt/walmart" set "REGISTRY_URL=gitea.digitoolsolutions.synology.me" + +:: Health-Check Polling Settings +set "HEALTH_PORT=3000" +set "HEALTH_PATH=/api/v1/system/health-check/" +set "HEALTH_INTERVAL=30" +set "HEALTH_MAX_RETRIES=10" + +:: Kiosk Local Assets set "KIOSK_APP_DIR=C:\KioskApp" :: ============================================================================ @@ -24,13 +34,34 @@ if %errorLevel% neq 0 ( ) echo ============================================================================ -echo DTS TORQUE VAULT - SYSTEM UPDATE (CONTAINERS AND KIOSK SHELL) +echo DTS TORQUE VAULT - PRODUCTION UPDATE MANAGER (ZERO-BASE64 EDITION) echo ============================================================================ echo. :: ============================================================================ -:: 1. PRE-FLIGHT CHECK +:: 1. PRE-FLIGHT CHECK: WSL, NETWORK & SOURCE FILES :: ============================================================================ +echo [1/4] Verifying WSL2 environment, Internet connection, and config files... + +wsl -d %WSL_DISTRO% -u root true >nul 2>&1 +if %errorLevel% neq 0 ( + echo [ERROR] %WSL_DISTRO% is not installed or not running. Run install.bat first! + pause + exit /b 1 +) + +if not exist "%ROOT_DIR%compose.yml" ( + echo [ERROR] Missing required file: "%ROOT_DIR%compose.yml" + pause + exit /b 1 +) + +if not exist "%ROOT_DIR%.env" ( + echo [ERROR] Missing required file: "%ROOT_DIR%.env" + pause + exit /b 1 +) + ping -n 1 8.8.8.8 >nul 2>&1 if %errorLevel% neq 0 ( echo [ERROR] No Internet connection detected! Connect LAN/Wi-Fi and run again. @@ -38,74 +69,90 @@ if %errorLevel% neq 0 ( exit /b 1 ) -wsl -d %WSL_DISTRO% -u root true >nul 2>&1 -if %errorLevel% neq 0 ( - echo [ERROR] WSL distribution "%WSL_DISTRO%" is not installed. Run install.bat first. - pause - exit /b 1 -) +:: ============================================================================ +:: 2. SYNC KIOSK STARTUP TEMPLATE & AUTHENTICATE REGISTRY +:: ============================================================================ +echo [2/4] Updating Kiosk startup screen and checking Docker registry login... -:: ============================================================================ -:: 2. UPDATE KIOSK STARTUP PAGE (IF PRESENT) -:: ============================================================================ -echo [1/4] Updating Kiosk startup template... if exist "%ROOT_DIR%templates\startup.html" ( if not exist "%KIOSK_APP_DIR%" mkdir "%KIOSK_APP_DIR%" copy /Y "%ROOT_DIR%templates\startup.html" "%KIOSK_APP_DIR%\startup.html" >nul - icacls "%KIOSK_APP_DIR%" /grant "Users:(OI)(CI)RX" /T >nul + icacls "%KIOSK_APP_DIR%" /grant "Users:(OI)(CI)RX" /T >nul 2>&1 echo - Updated %KIOSK_APP_DIR%\startup.html -) else ( - echo - Skipped (templates\startup.html not found in package) ) -:: ============================================================================ -:: 3. SYNC COMPOSE.YML AND .ENV INTO WSL -:: ============================================================================ -echo [2/4] Syncing compose.yml and .env to %PROJECT_DIR%... -for /f "delims=" %%i in ('wsl -d %WSL_DISTRO% -u root wslpath -a "%CLEAN_ROOT%"') do set "WSL_ROOT_DIR=%%i" - -if exist "%ROOT_DIR%compose.yml" ( - wsl -d %WSL_DISTRO% -u root bash -c "mkdir -p %PROJECT_DIR% && cp '%WSL_ROOT_DIR%/compose.yml' %PROJECT_DIR%/" - echo - Synced compose.yml -) - -if exist "%ROOT_DIR%.env" ( - wsl -d %WSL_DISTRO% -u root bash -c "cp '%WSL_ROOT_DIR%/.env' %PROJECT_DIR%/ && sed -i 's/\r$//' %PROJECT_DIR%/.env" - echo - Synced and normalized .env -) else ( - echo - Kept existing %PROJECT_DIR%/.env on device -) - -:: ============================================================================ -:: 4. PULL LATEST DOCKER IMAGES AND RECREATE CONTAINERS -:: ============================================================================ -echo [3/4] Pulling latest Docker images and recreating containers... -wsl -d %WSL_DISTRO% -u root service docker start >nul 2>&1 wsl -d %WSL_DISTRO% -u root docker login %REGISTRY_URL% if %errorLevel% neq 0 ( - echo [ERROR] Docker registry login failed. - pause - exit /b 1 -) - -wsl -d %WSL_DISTRO% -u root bash -c "cd %PROJECT_DIR% && docker compose pull && docker compose up -d --remove-orphans" -if %errorLevel% neq 0 ( - echo [ERROR] Failed to update Docker containers. + echo [ERROR] Docker registry login failed for %REGISTRY_URL%. pause exit /b 1 ) :: ============================================================================ -:: 5. CLEANUP UNUSED DOCKER IMAGES +:: 3. PULL LATEST IMAGES, RECREATE CONTAINERS & VERIFY HEALTH-CHECK (PORT 3000) :: ============================================================================ -echo [4/4] Cleaning up dangling/unused Docker images... -wsl -d %WSL_DISTRO% -u root docker image prune -f >nul 2>&1 +echo [3/4] Pulling latest images, updating containers, and verifying Online status... + +for /f "delims=" %%i in ('wsl -d %WSL_DISTRO% -u root wslpath -a "%CLEAN_ROOT%"') do set "WSL_ROOT_DIR=%%i" + +set "UPDATE_SH=%TEMP%\dts_update.sh" +> "%UPDATE_SH%" echo set -e +>> "%UPDATE_SH%" echo SRC_DIR="$1" +>> "%UPDATE_SH%" echo PROJ_DIR="$2" +>> "%UPDATE_SH%" echo PROJ_NAME="$3" +>> "%UPDATE_SH%" echo PORT="$4" +>> "%UPDATE_SH%" echo ENDPOINT="$5" +>> "%UPDATE_SH%" echo INTERVAL="$6" +>> "%UPDATE_SH%" echo MAX_RETRIES="$7" +>> "%UPDATE_SH%" echo. +>> "%UPDATE_SH%" echo systemctl is-active --quiet docker ^|^| service docker start +>> "%UPDATE_SH%" echo mkdir -p "$PROJ_DIR" +>> "%UPDATE_SH%" echo cp "$SRC_DIR/compose.yml" "$PROJ_DIR/compose.yml" +>> "%UPDATE_SH%" echo tr -d '\r' ^< "$SRC_DIR/.env" ^> "$PROJ_DIR/.env" +>> "%UPDATE_SH%" echo. +>> "%UPDATE_SH%" echo cd "$PROJ_DIR" +>> "%UPDATE_SH%" echo echo " - Pulling latest container images from registry..." +>> "%UPDATE_SH%" echo docker compose -p "$PROJ_NAME" pull +>> "%UPDATE_SH%" echo echo " - Recreating updated containers (preserving database volumes)..." +>> "%UPDATE_SH%" echo docker compose -p "$PROJ_NAME" up -d --remove-orphans +>> "%UPDATE_SH%" echo. +>> "%UPDATE_SH%" echo echo " - Polling http://localhost:${PORT}${ENDPOINT} every ${INTERVAL}s (max ${MAX_RETRIES} attempts)..." +>> "%UPDATE_SH%" echo for i in $(seq 1 "$MAX_RETRIES"); do +>> "%UPDATE_SH%" echo RES=$(curl -kfsS --max-time 3 "http://localhost:${PORT}${ENDPOINT}" 2^>/dev/null ^|^| true) +>> "%UPDATE_SH%" echo if echo "$RES" ^| grep -qi "Online"; then +>> "%UPDATE_SH%" echo echo " - Update verified: Server is Online and database migrations are complete!" +>> "%UPDATE_SH%" echo exit 0 +>> "%UPDATE_SH%" echo fi +>> "%UPDATE_SH%" echo echo " - Attempt $i/$MAX_RETRIES: Server is still restarting/migrating, retrying in ${INTERVAL}s..." +>> "%UPDATE_SH%" echo sleep "$INTERVAL" +>> "%UPDATE_SH%" echo done +>> "%UPDATE_SH%" echo echo " - [ERROR] Timed out waiting for Server on port $PORT to become Online!" +>> "%UPDATE_SH%" echo exit 1 + +for /f "delims=" %%i in ('wsl -d %WSL_DISTRO% -u root wslpath -a "%UPDATE_SH%"') do set "WSL_UPDATE_SH=%%i" +wsl -d %WSL_DISTRO% -u root bash -c "tr -d '\r' < '%WSL_UPDATE_SH%' > /tmp/dts_update.sh && bash /tmp/dts_update.sh '%WSL_ROOT_DIR%' '%PROJECT_DIR%' '%PROJECT_NAME%' '%HEALTH_PORT%' '%HEALTH_PATH%' '%HEALTH_INTERVAL%' '%HEALTH_MAX_RETRIES%'; RC=$?; rm -f /tmp/dts_update.sh; exit $RC" +set "UPDATE_ERR=%errorLevel%" +del /f /q "%UPDATE_SH%" >nul 2>&1 + +if %UPDATE_ERR% neq 0 ( + echo [ERROR] Update or server health-check failed! + echo Inspect backend logs with: wsl -d %WSL_DISTRO% -u root docker logs tv-backend-prod + pause + exit /b 1 +) + +:: ============================================================================ +:: 4. CLEAN UP DANGLING DOCKER IMAGES & SHOW CONTAINER STATUS +:: ============================================================================ +echo [4/4] Cleaning up unused old Docker images and checking container status... +wsl -d %WSL_DISTRO% -u root bash -c "docker image prune -f >/dev/null 2>&1 && cd '%PROJECT_DIR%' && docker compose -p '%PROJECT_NAME%' ps" echo. echo ============================================================================ echo UPDATE COMPLETED SUCCESSFULLY! -echo - All containers are up to date and running in %PROJECT_DIR% -echo - Database and Kiosk user configuration were preserved +echo - Project / Directory : %PROJECT_NAME% (%PROJECT_DIR%) +echo - Backend Health : Verified Online on Port %HEALTH_PORT% +echo - Database Volumes : Preserved safely echo ============================================================================ echo. pause \ No newline at end of file