4 Commits
Author SHA1 Message Date
lamtruong28 4b9c8a87ec Update scripts 2026-11-18 14:52:16 +07:00
lamtruong28 e74d2eff3c Allow enter username and password for WSL account 2026-11-16 22:59:54 +07:00
lamtruong28 62100913ae [Fix] Auto start WSL 2026-11-15 18:15:00 +07:00
lamtruong28 f23e85f348 Test and update scripts on mini pc 2026-11-15 12:47:38 +07:00
10 changed files with 716 additions and 346 deletions
+4 -4
View File
@@ -1,11 +1,11 @@
# Frontend environments # Frontend environments
VITE_PORT = VITE_PORT = 3000
VITE_API_BASE_URL = VITE_API_BASE_URL = /api/v1/
VITE_API_WS_URL = VITE_API_WS_URL = /ws/
VITE_SECURITY_CODE = VITE_SECURITY_CODE =
# Backend environments # Backend environments
DEBUG = DEBUG = False
SECRET_KEY = SECRET_KEY =
ALLOWED_HOSTS = ALLOWED_HOSTS =
PER_PAGE_SIZE = PER_PAGE_SIZE =
+8
View File
@@ -0,0 +1,8 @@
# File batch Windows CRLF (\r\n)
*.bat text eol=crlf
*.ps1 text eol=crlf
# shell script Linux and compose always use LF (\n)
*.sh text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
+12 -11
View File
@@ -1,6 +1,6 @@
# DTS Torque Vault — Mini PC Kiosk Commissioning & QA Checklist # DTS Torque Vault — Mini PC Kiosk Commissioning & QA Checklist
Use this checklist to verify and sign off each Mini PC after running `scripts\install.bat`. Use this checklist to verify and sign off each Mini PC after running `setup.bat` / `scripts\install.bat`.
--- ---
@@ -18,8 +18,8 @@ Use this checklist to verify and sign off each Mini PC after running `scripts\in
## 1. Pre-Deployment & Package Verification ## 1. Pre-Deployment & Package Verification
- [ ] Deployment package extracted locally to `C:\Apps\mini-pc-setup\` (via `scripts\setup.bat` or manual archive extraction). - [ ] Deployment package extracted locally to `C:\Apps\mini-pc-setup\` (via `setup.bat`, `bootstrap.ps1`, or manual release extraction).
- [ ] All required files present: `scripts\install.bat`, `scripts\update.bat`, `scripts\uninstall.bat`, `templates\startup.html`, `compose.yml`, `.env`, `Readme.md`, and `CheckList.md`. - [ ] All required files present: `setup.bat`, `bootstrap.ps1`, `scripts\install.bat`, `scripts\update.bat`, `scripts\uninstall.bat`, `templates\startup.html`, `compose.yml`, `.env`, `README.md`, and `CheckList.md`.
- [ ] BIOS Hardware Virtualization (`Intel VT-x` / `AMD-V`) verified as **Enabled**. - [ ] BIOS Hardware Virtualization (`Intel VT-x` / `AMD-V`) verified as **Enabled**.
- [ ] Active LAN / Wi-Fi connection confirmed. - [ ] Active LAN / Wi-Fi connection confirmed.
@@ -27,21 +27,22 @@ Use this checklist to verify and sign off each Mini PC after running `scripts\in
## 2. WSL2 & Docker Backend Verification ## 2. WSL2 & Docker Backend Verification
_(Sign in as **Administrator** via `Ctrl + Alt + Del` → **Switch user** to run these checks if needed)_ _(Sign in as **Administrator** to run these checks if needed)_
- [ ] `Ubuntu-22.04` WSL2 distribution is installed with `systemd=true` in `/etc/wsl.conf`. - [ ] `Ubuntu-22.04` WSL2 distribution is installed with `systemd=true` in `/etc/wsl.conf` and `vmIdleTimeout=-1` in `%USERPROFILE%\.wslconfig`.
- [ ] Docker Engine `28.3.2` and Docker Compose V2 are installed and pinned (`apt-mark hold`). - [ ] Docker Engine `28.3.2` and Docker Compose V2 are installed and pinned (`apt-mark hold`).
- [ ] All containers in `/opt/walmart` show status **`Up`** (`wsl -d Ubuntu-22.04 -u root bash -c "docker ps"`). - [ ] All containers in `/opt/walmart` (`-p walmart`) show status **`Up`** (`wsl -d Ubuntu-22.04 -u root bash -c "docker ps"`).
- [ ] Scheduled Task **`DTS_WSL_Docker_AutoStart`** exists, runs at startup (`AtStartup`), and executes under **`SYSTEM`**. - [ ] Backend health endpoint `http://localhost:3000/api/v1/system/health-check/` returns **`Online`**.
- [ ] Scheduled Task **`WSL Docker Startup`** exists, triggers **At startup**, runs under the **Administrator** account (_Run whether user is logged on or not_, **not** `SYSTEM`), and has **Stop the task if it runs longer than** & **AC power** conditions **unchecked**.
--- ---
## 3. Kiosk Mode, Auto-Logon & Session Persistence ## 3. Kiosk Mode, Auto-Logon & Session Persistence
- [ ] **Cold Boot / Reboot Test:** Restart the Mini PC and verify it bypasses the Windows login screen and automatically signs into the Kiosk account. - [ ] **Cold Boot / Reboot Test:** Restart the Mini PC and verify it bypasses the Windows login screen and automatically signs into the Kiosk account (`Torque Vault`).
- [ ] **UI Lockdown:** Windows Desktop, Start Menu, and Taskbar are completely hidden; Microsoft Edge launches full-screen on `C:\KioskApp\startup.html` and transitions smoothly into the main application. - [ ] **UI Lockdown:** Windows Desktop, Start Menu, and Taskbar are completely hidden; Microsoft Edge launches full-screen on `C:\KioskApp\startup.html` and transitions smoothly into `http://localhost:3000`.
- [ ] **Session Persistence Test:** Log into the web application inside Kiosk mode, reboot the Mini PC, and confirm the browser session/cookies in `C:\KioskBrowserData` remain intact (no forced re-login). - [ ] **Session Persistence Test:** Log into the web application inside Kiosk mode, reboot the Mini PC, and confirm the browser session/cookies in `C:\KioskBrowserData` remain intact (no forced re-login).
- [ ] **Admin Escape Hatch:** Pressing `Ctrl + Alt + Del` → **Switch user** allows signing into the **Administrator** account with a normal Windows Desktop intact. - [ ] **Admin Escape Hatch:** Pressing `Ctrl + Alt + Del` → **Switch user** (or turning the display off/on and swiping up the Lock Screen on touch-only kiosks) allows signing into the **Administrator** account with a normal Windows Desktop intact.
--- ---
@@ -59,4 +60,4 @@ _(Sign in as **Administrator** via `Ctrl + Alt + Del` → **Switch user** to run
- [ ] **PASS — Unit approved for production deployment.** - [ ] **PASS — Unit approved for production deployment.**
**Technician Signature:** `___________________________`     **Date:** `____ / ____ / 2026` **Technician Signature:** `___________________________`     **Date:** `____ / ____ / ____`
+74 -67
View File
@@ -1,93 +1,100 @@
# DTS Torque Vault — Mini PC Kiosk Deployment & Maintenance Guide (24/7) # DTS Torque Vault — Mini PC Kiosk 24/7 Deployment
Automated, idempotent deployment scripts to provision a fresh Windows Mini PC into a dedicated **24/7 Kiosk appliance** running WSL2 (`Ubuntu-22.04`), Docker Engine `28.3.2`, and full-screen Microsoft Edge with persistent session storage. Automated, zero-touch deployment suite for provisioning Windows 10/11 Mini PCs into dedicated 24/7 Kiosk terminals running **DTS Torque Vault** on WSL2 (`Ubuntu-22.04`) and Docker Engine.
--- ---
## 1. Repository & Deployment Structure ## Repository Structure
mini-pc-setup/ mini-pc-setup/
├── .gitignore # Prevents committing real .env credentials ├── setup.bat # One-click Windows bootstrapper (downloads & extracts latest release)
├── .env.template # Environment variable template (copied to .env on setup) ├── bootstrap.ps1 # PowerShell release downloader & .env initializer
├── compose.yml # Docker Compose service definitions ├── compose.yml # Docker Compose service definitions (project: walmart)
├── Readme.md # Technician deployment & maintenance guide ├── .env.template # Environment variable template (copied to .env if missing)
├── CheckList.md # Unit commissioning & QA sign-off checklist ├── README.md # Deployment & maintenance guide
├── templates/ ├── scripts/
│ └── startup.html # Kiosk splash/health-check screen before app redirect │ ├── install.bat # Master 7-phase Kiosk & WSL2/Docker installer
└── scripts/ │ ├── update.bat # Zero-downtime container & image updater (preserves DB volumes)
├── setup.bat # 1-click Gitea Latest Release bootstrapper for technicians │ └── uninstall.bat # Full system restore & Kiosk uninstaller (Auto Wipe or Custom)
├── bootstrap.ps1 # Downloads Latest Release to C:\Apps\mini-pc-setup\ └── templates/
├── install.bat # Master all-in-one deployment script └── startup.html # Local Kiosk splash/health-check screen before redirecting to :3000
├── update.bat # Updates containers, configs, and startup.html
└── uninstall.bat # Reverts Kiosk mode and restores normal Windows
> **Critical Pre-Deployment Notes**
>
> - **Administrator & Internet:** Sign in using a local **Administrator** account with an active Internet connection.
> - **BIOS Virtualization:** Hardware Virtualization (`Intel VT-x` or `AMD-V`) must be enabled in BIOS.
> - **Local Execution:** All files are extracted to `C:\Apps\mini-pc-setup\` so installation survives the mandatory WSL2 reboot without requiring a USB drive to remain plugged in.
--- ---
## 2. Fresh Mini PC Installation ## Prerequisites
### Option A: 1-Click Deployment via Gitea Latest Release _(Recommended)_ - **OS:** Windows 10 (21H2+) or Windows 11 (64-bit) with **Microsoft Edge** installed.
- **BIOS / Firmware:** Hardware Virtualization (`Intel VT-x` / `AMD-V`) **Enabled**.
1. Copy **`scripts\setup.bat`** onto the Mini PC (or download it from the Gitea Release Assets). - **Privileges:** Local Administrator account on the Mini PC.
2. Double-click **`setup.bat`** and click **Yes** on the UAC Administrator prompt. - **Network:** Internet access to download Ubuntu/Docker packages and pull images from `gitea.digitoolsolutions.synology.me`.
- If the repository is **Private**, enter your Gitea credentials once when prompted.
3. The bootstrapper downloads the Latest Release into `C:\Apps\mini-pc-setup\`, copies `.env.template` to `.env` (opening Notepad so you can configure site-specific values), and launches `scripts\install.bat`.
### Option B: Manual Deployment from `C:\Apps\mini-pc-setup\`
1. Extract the release package to `C:\Apps\mini-pc-setup\`.
2. Double-click **`scripts\install.bat`** (auto-creates `.env` from `.env.template` if missing).
### Installation Phases (`scripts\install.bat`)
1. **Pre-Flight Checks:** Verifies `templates\startup.html`, `compose.yml`, `.env`, Microsoft Edge, Internet access, and BIOS Virtualization.
2. **Phase 1 — WSL2 & Ubuntu-22.04 _(First-time setup only)_:** Installs WSL2 + `Ubuntu-22.04`, registers a `RunOnce` resume entry, and reboots. Sign back in as **Administrator** and the installer automatically resumes.
3. **Phase 2 — Docker, Containers & Kiosk Setup:**
- Logs into `gitea.digitoolsolutions.synology.me`, deploys containers to `/opt/walmart`, and registers the `DTS_WSL_Docker_AutoStart` (`SYSTEM`) boot task.
- Prompts for the Kiosk username (default: `Torque Vault`) and optional password _(avoid Batch special characters `&`, `|`, `<`, `>`, `^`, `%`)_. If switching to a new Kiosk username, the previous Kiosk user's normal Windows Desktop is automatically restored.
- Hardens 24/7 operation: activates **High Performance** power plan, disables **Sleep**, **Hibernate**, **Display Timeout**, and **USB Selective Suspend**, and blocks Windows Update auto-reboots while logged on.
4. **Final Reboot:** Type `Y` and press **Enter**. The Mini PC boots directly into the full-screen Kiosk application.
--- ---
## 3. Switching to Administrator for Maintenance ## Quick Start (Fresh Mini PC Deployment)
While the Mini PC is running in full-screen Kiosk mode: 1. Copy **`setup.bat`** onto the Mini PC (or download it directly from Gitea) and double-click to run it (automatically elevates to Administrator).
2. `setup.bat` performs the following automatically:
1. Press **`Ctrl + Alt + Del`**. - Verifies DNS and connectivity to `[https://gitea.digitoolsolutions.synology.me](https://gitea.digitoolsolutions.synology.me)`.
2. Click **Switch user**. - Fetches the latest published release of `lamtruong28/mini-pc-setup` (prompts for Gitea credentials only if the repository/release is private).
3. Select the **Administrator** account in the bottom-left corner and sign in. - Extracts all release assets (including hidden files such as `.env`) into **`C:\Apps\mini-pc-setup`**.
- Launches `scripts\install.bat`.
3. **If WSL2 / `Ubuntu-22.04` is not installed yet:**
- Phase 1 installs WSL2 and `Ubuntu-22.04`, registers a `RunOnce` resume entry, and prompts to **reboot** the Mini PC.
- Log back in as Administrator after reboot — `install.bat` resumes automatically.
4. **During installation (`install.bat`):**
- If `.env` does not exist, it is created from `.env.template` and opened in Notepad for configuration.
- Enter your Gitea registry credentials when prompted by `docker login`.
- Choose the Windows Kiosk account name (**Default:** `Torque Vault`) and password (**Default:** blank / no password).
5. When prompted at the end, enter **`Y`** to reboot immediately into **Fullscreen Edge Kiosk Mode**.
--- ---
## 4. Updating the Application (`scripts\update.bat`) ## What `install.bat` Configures
1. Switch to the **Administrator** account (see [Section 3](#3-switching-to-administrator-for-maintenance)). | Phase | Component | Configuration Details |
2. Update `compose.yml`, `.env`, or `templates\startup.html` in `C:\Apps\mini-pc-setup\` if changed. | :------------ | :---------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
3. Double-click **`scripts\update.bat`**. | **Pre-Check** | Environment & Security | Verifies Edge, `compose.yml`, `.env`, `templates\startup.html`, Internet, BIOS Virtualization, and locks `C:\Apps\mini-pc-setup` ACLs to `Administrators` and `SYSTEM`. |
4. **Verification:** Confirm all 4 steps complete and `docker ps` shows all containers in the `Up` state. Reboot to reload the Kiosk UI. | **Phase 1–2** | WSL2 (`Ubuntu-22.04`) | Installs `Ubuntu-22.04`, creates `dtsadmin` with passwordless `sudo`, enables `systemd=true`, and sets `vmIdleTimeout=-1` in `.wslconfig`. |
| **Phase 3** | Docker Engine | Installs and holds pinned `docker-ce` (`5:28.3.2-1~ubuntu.22.04~jammy`) + `docker-compose-plugin`. |
| **Phase 4** | App Deployment | Deploys stack under `-p walmart` in `/opt/walmart` and polls `http://localhost:3000/api/v1/system/health-check/` every 30s until `"Online"` is returned. |
| **Phase 5–6** | Kiosk Shell & Boot Task | Creates `Torque Vault` user, sets Windows `AutoAdminLogon`, locks user `Shell` policy directly to fullscreen Edge (`C:\KioskApp\startup.html` → `http://localhost:3000`), and registers the **`WSL Docker Startup`** Task Scheduler job (`AtStartup`, `S4U`, unlimited runtime) running `C:\KioskApp\start_wsl_docker.bat`. |
| **Phase 7** | 24/7 Hardening | Activates High Performance power plan, disables sleep/hibernate/display/disk timeouts, and blocks automatic Windows Update reboots while logged on. |
--- ---
## 5. Uninstalling / Restoring Normal Windows Mode (`scripts\uninstall.bat`) ## Maintenance & Operations
1. Switch to the **Administrator** account (see [Section 3](#3-switching-to-administrator-for-maintenance)). ### Updating the Application (`scripts\update.bat`)
2. Double-click **`scripts\uninstall.bat`**.
3. Answer the cleanup prompts (`Y`/`N`) for deleting the Kiosk user account, removing `C:\KioskApp` & `C:\KioskBrowserData`, and unregistering `Ubuntu-22.04`. To update container images, `compose.yml`, `.env`, or `templates\startup.html` without losing database data:
4. Type `Y` to reboot. Windows returns to the standard login screen with Auto-Logon disabled and the power plan reset to **Balanced**.
1. Log in to the Administrator account (press `Ctrl + Alt + Del` → **Sign out** or **Switch user**).
2. Update `.env` or `compose.yml` inside `C:\Apps\mini-pc-setup` if needed.
3. Run **`C:\Apps\mini-pc-setup\scripts\update.bat`** as Administrator:
- Syncs `startup.html`, `compose.yml`, and `.env` (converting CRLF to LF).
- Runs `docker compose -p walmart pull` and `up -d --remove-orphans` (preserving database volumes).
- Verifies `/api/v1/system/health-check/` reports `Online` and prunes dangling Docker images.
### Uninstalling & Restoring Desktop (`scripts\uninstall.bat`)
Run **`C:\Apps\mini-pc-setup\scripts\uninstall.bat`** as Administrator and select a mode:
- **`[1] Auto Wipe All`:** Automatically disables Auto-Logon, deletes the Kiosk user and browser profile (`C:\KioskBrowserData`), removes scheduled tasks and `C:\KioskApp`, tears down Docker containers and volumes (`down -v`), restores Balanced power plan, and deletes `C:\Apps\mini-pc-setup`.
- **`[2] Manual / Custom`:** Prompts step-by-step whether to delete or restore the Kiosk user's normal Windows Desktop (`explorer.exe`), keep browser data, preserve database volumes, or keep the setup folder.
--- ---
## 6. Quick Troubleshooting ## Troubleshooting
| Symptom | Resolution | - **Web app (`http://localhost:3000`) is unreachable after reboot:**
| :------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------- | ------------------------- | - Open **Task Scheduler** as Administrator and check **`WSL Docker Startup`**. Ensure it is configured to run under the Administrator account that installed WSL2 (not `SYSTEM`) with _"Run whether user is logged on or not"_ enabled.
| **`Hardware Virtualization is DISABLED in BIOS`** | Reboot into BIOS/UEFI, enable **Intel VT-x** or **AMD-V**, save, and re-run `scripts\install.bat`. | - Inspect backend container logs inside WSL:
| **Kiosk stays on `startup.html` for > 1 minute** | Verify LAN/Wi-Fi connectivity. Switch to Administrator and run `scripts\update.bat` to verify containers in `/opt/walmart`. |
| **Stops at Windows login screen (no Auto-Logon)** | Sign in as Administrator and re-run `scripts\install.bat`. Ensure the Kiosk password does not contain `&`, ` | `, `<`, `>`, `^`, or `%`. | wsl -d Ubuntu-22.04 -u root docker logs tv-backend-prod
| **USB Dongle / Scanner disconnects when idle** | Re-run `scripts\install.bat` to ensure **High Performance** is active and **USB Selective Suspend** is **Disabled**. |
- **Exiting Kiosk Mode for Admin Maintenance:**
- **With a physical keyboard:** Press **`Ctrl + Alt + Del`** → **Switch user** → sign in with your Administrator account.
- **Touchscreen only (no physical keyboard):**
1. Turn the display off and back on (or press the physical power/sleep button briefly to lock the screen).
2. Swipe up on the Windows Lock Screen to reveal the sign-in screen.
3. Tap the **Administrator** account in the bottom-left corner, tap the password box (Windows On-Screen Touch Keyboard will appear automatically), and sign in.
-79
View File
@@ -1,79 +0,0 @@
param(
[string]$GiteaUrl = "https://gitea.digitoolsolutions.synology.me",
[string]$Owner = "lamtruong28",
[string]$Repo = "mini-pc-setup",
[object]$ReleaseJson = $null,
[pscredential]$Credential = $null
)
$ErrorActionPreference = "Stop"
$GiteaUrl = $GiteaUrl.TrimEnd('/')
$TargetDir = "C:\Apps\mini-pc-setup"
$TempZip = "$env:TEMP\mini-pc-setup-release.zip"
$TempExtract = "$env:TEMP\mini-pc-release-extract"
Write-Host "========================================================" -ForegroundColor Cyan
Write-Host " DTS TORQUE VAULT - DOWNLOADING LATEST RELEASE" -ForegroundColor Cyan
Write-Host "========================================================" -ForegroundColor Cyan
if ($null -eq $ReleaseJson) {
$apiUrl = "$GiteaUrl/api/v1/repos/$Owner/$Repo/releases/latest"
try {
$ReleaseJson = Invoke-RestMethod -Uri $apiUrl -UseBasicParsing
} catch {
Write-Host "[AUTH] Private repository detected. Please sign in to Gitea:" -ForegroundColor Yellow
$Credential = Get-Credential -Message "Enter Gitea Credentials"
$ReleaseJson = Invoke-RestMethod -Uri $apiUrl -Credential $Credential -UseBasicParsing
}
}
$TagName = $ReleaseJson.tag_name
Write-Host "[INFO] Latest Release Tag: $TagName ($($ReleaseJson.name))" -ForegroundColor Green
$ZipAsset = $ReleaseJson.assets | Where-Object { $_.name -like "*.zip" } | Select-Object -First 1
if ($null -ne $ZipAsset) {
$DownloadUrl = $ZipAsset.browser_download_url
Write-Host "[1/3] Downloading attached release asset: $($ZipAsset.name)..."
} else {
$DownloadUrl = $ReleaseJson.zipball_url
Write-Host "[1/3] Downloading release archive ($TagName)..."
}
if (-not (Test-Path $TargetDir)) {
New-Item -ItemType Directory -Path $TargetDir -Force | Out-Null
}
if ($null -ne $Credential) {
Invoke-WebRequest -Uri $DownloadUrl -OutFile $TempZip -Credential $Credential -UseBasicParsing
} else {
Invoke-WebRequest -Uri $DownloadUrl -OutFile $TempZip -UseBasicParsing
}
Write-Host "[2/3] Extracting files to $TargetDir..."
if (Test-Path $TempExtract) { Remove-Item $TempExtract -Recurse -Force }
Expand-Archive -Path $TempZip -DestinationPath $TempExtract -Force
$TopDirs = Get-ChildItem -Path $TempExtract -Directory
$TopFiles = Get-ChildItem -Path $TempExtract -File
if ($TopFiles.Count -eq 0 -and $TopDirs.Count -eq 1) {
Copy-Item -Path "$($TopDirs[0].FullName)\*" -Destination $TargetDir -Recurse -Force
} else {
Copy-Item -Path "$TempExtract\*" -Destination $TargetDir -Recurse -Force
}
Remove-Item $TempZip -Force -ErrorAction SilentlyContinue
Remove-Item $TempExtract -Recurse -Force -ErrorAction SilentlyContinue
# Auto-create .env from .env.template if .env does not exist yet
if (-not (Test-Path "$TargetDir\.env") -and (Test-Path "$TargetDir\.env.template")) {
Copy-Item "$TargetDir\.env.template" "$TargetDir\.env"
Write-Host "[ACTION REQUIRED] Please configure '.env' in Notepad, save, and close it to continue..." -ForegroundColor Yellow
Start-Process notepad.exe "$TargetDir\.env" -Wait
}
Write-Host "[3/3] Launching scripts\install.bat..." -ForegroundColor Green
$InstallScript = "$TargetDir\scripts\install.bat"
if (-not (Test-Path $InstallScript)) {
throw "Cannot find $InstallScript after extraction!"
}
Start-Process -FilePath "cmd.exe" -ArgumentList "/c `"$InstallScript`"" -WorkingDirectory "$TargetDir\scripts"
+331 -77
View File
@@ -2,18 +2,31 @@
setlocal EnableDelayedExpansion setlocal EnableDelayedExpansion
:: ============================================================================ :: ============================================================================
:: CONFIGURATION (RESOLVE PARENT ROOT DIRECTORY FROM /scripts) :: CONFIGURATION (EDIT THESE VARIABLES DIRECTLY)
:: ============================================================================ :: ============================================================================
set "SCRIPT_DIR=%~dp0" set "SCRIPT_DIR=%~dp0"
for %%I in ("%SCRIPT_DIR%..") do set "ROOT_DIR=%%~fI\" 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_DISTRO=Ubuntu-22.04"
set "DEFAULT_WSL_USER=gateway"
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 "PROJECT_DIR=/opt/walmart"
set "REGISTRY_URL=gitea.digitoolsolutions.synology.me" 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, Power & Edge Settings
set "DEFAULT_KIOSK_USER=Torque Vault" set "DEFAULT_KIOSK_USER=Torque Vault"
set "KIOSK_APP_DIR=C:\KioskApp" set "KIOSK_APP_DIR=C:\KioskApp"
set "KIOSK_DATA_DIR=C:\KioskBrowserData" set "KIOSK_DATA_DIR=C:\KioskBrowserData"
set "DEFAULT_DISPLAY_OFF_MINUTES=15"
set "EDGE_EXE=C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" set "EDGE_EXE=C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
if not exist "%EDGE_EXE%" set "EDGE_EXE=C:\Program Files\Microsoft\Edge\Application\msedge.exe" if not exist "%EDGE_EXE%" set "EDGE_EXE=C:\Program Files\Microsoft\Edge\Application\msedge.exe"
@@ -44,13 +57,26 @@ pause
exit /b 1 exit /b 1
:EDGE_OK :EDGE_OK
if exist "%ROOT_DIR%.env" goto :ENV_OK if exist "%ROOT_DIR%.env" goto :ENV_CLEANUP
if exist "%ROOT_DIR%.env.template" (
copy /Y "%ROOT_DIR%.env.template" "%ROOT_DIR%.env" >nul set "ENV_SAMPLE="
echo [ACTION REQUIRED] Created .env from .env.template. Configure it in Notepad, save, and close... if exist "%ROOT_DIR%.env.example" set "ENV_SAMPLE=%ROOT_DIR%.env.example"
start /wait notepad.exe "%ROOT_DIR%.env" if "%ENV_SAMPLE%"=="" if exist "%ROOT_DIR%.env.template" set "ENV_SAMPLE=%ROOT_DIR%.env.template"
if "%ENV_SAMPLE%"=="" goto :ENV_CLEANUP
copy /Y "%ENV_SAMPLE%" "%ROOT_DIR%.env" >nul
echo [ACTION REQUIRED] Created .env from sample. Configure it in Notepad, save, and close...
start /wait notepad.exe "%ROOT_DIR%.env"
:ENV_CLEANUP
if not exist "%ROOT_DIR%.env" (
echo [ERROR] Missing required file: "%ROOT_DIR%.env"
pause
exit /b 1
) )
:ENV_OK attrib +h "%ROOT_DIR%.env" >nul 2>&1
if exist "%ROOT_DIR%.env.example" del /f /q "%ROOT_DIR%.env.example" >nul 2>&1
if exist "%ROOT_DIR%.env.template" del /f /q "%ROOT_DIR%.env.template" >nul 2>&1
if not exist "%ROOT_DIR%templates\startup.html" ( if not exist "%ROOT_DIR%templates\startup.html" (
echo [ERROR] Missing required file: "%ROOT_DIR%templates\startup.html" echo [ERROR] Missing required file: "%ROOT_DIR%templates\startup.html"
@@ -62,11 +88,9 @@ if not exist "%ROOT_DIR%compose.yml" (
pause pause
exit /b 1 exit /b 1
) )
if not exist "%ROOT_DIR%.env" (
echo [ERROR] Missing required file: "%ROOT_DIR%.env" :: Restrict setup directory permissions to Administrators and SYSTEM to protect .env
pause icacls "%CLEAN_ROOT%" /inheritance:r /grant:r "Administrators:(OI)(CI)F" "SYSTEM:(OI)(CI)F" >nul 2>&1
exit /b 1
)
ping -n 1 8.8.8.8 >nul 2>&1 ping -n 1 8.8.8.8 >nul 2>&1
if %errorLevel% neq 0 ( if %errorLevel% neq 0 (
@@ -75,7 +99,10 @@ if %errorLevel% neq 0 (
exit /b 1 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 ( if %errorLevel% neq 0 (
echo [ERROR] Hardware Virtualization is DISABLED in BIOS! echo [ERROR] Hardware Virtualization is DISABLED in BIOS!
echo Please reboot into BIOS, enable Virtualization, and run again. echo Please reboot into BIOS, enable Virtualization, and run again.
@@ -87,83 +114,209 @@ echo - Pre-flight checks passed!
echo. echo.
:: ============================================================================ :: ============================================================================
:: PHASE 1: CHECK & INSTALL WSL2 + UBUNTU-22.04 (ENFORCES REQUIRED REBOOT) :: PHASE 1: CHECK & INSTALL WSL2 + UBUNTU-22.04 (ENFORCES SINGLE REBOOT)
:: ============================================================================ :: ============================================================================
schtasks /delete /tn "DTS_Master_Setup_Resume" /f >nul 2>&1
wsl -d %WSL_DISTRO% -u root true >nul 2>&1 wsl -d %WSL_DISTRO% -u root true >nul 2>&1
if %errorLevel% equ 0 goto :PHASE1_DONE
echo [PHASE 1] Checking WSL2 / %WSL_DISTRO% status...
powershell -NoProfile -Command "$d = wsl -l -q 2>$null; if ($d -match '%WSL_DISTRO%') { exit 0 } else { exit 1 }"
if %errorLevel% neq 0 ( if %errorLevel% neq 0 (
wsl -l -q 2>nul | findstr /i "%WSL_DISTRO%" >nul echo - Installing %WSL_DISTRO%...
wsl --install -d %WSL_DISTRO% --no-launch
if !errorLevel! neq 0 ( if !errorLevel! neq 0 (
echo [PHASE 1] WSL2 / %WSL_DISTRO% not found. Installing now... echo [ERROR] WSL installation failed. Ensure Virtualization is enabled in BIOS.
wsl --install -d %WSL_DISTRO% --no-launch pause
if !errorLevel! neq 0 ( exit /b 1
echo [ERROR] WSL installation failed. Ensure Virtualization is enabled in BIOS.
pause
exit /b 1
)
) else (
echo [PHASE 1] %WSL_DISTRO% is staged, but Windows has NOT rebooted yet!
) )
goto :PHASE1_NEED_REBOOT
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v "DTS_Master_Setup" /t REG_SZ /d "\"%~f0\"" /f >nul
echo.
echo ============================================================================
echo [REBOOT REQUIRED] Windows must restart to activate WSL2 kernel.
echo This installer will resume automatically after you log back in as Admin.
echo ============================================================================
echo.
pause
shutdown /r /t 3
exit /b
) )
if exist "%TEMP%\dts_wsl_rebooted.flag" (
echo [ERROR] %WSL_DISTRO% is installed but failed to boot even after reboot.
echo Run "wsl -d %WSL_DISTRO%" manually to inspect the exact WSL error.
del /f /q "%TEMP%\dts_wsl_rebooted.flag" >nul 2>&1
pause
exit /b 1
)
:PHASE1_NEED_REBOOT
echo 1 > "%TEMP%\dts_wsl_rebooted.flag"
schtasks /create /tn "DTS_Master_Setup_Resume" /tr "cmd.exe /c \"\"%~f0\"\"" /sc ONLOGON /ru "%USERDOMAIN%\%USERNAME%" /rl HIGHEST /f >nul 2>&1
echo.
echo ============================================================================
echo [REBOOT REQUIRED] Windows must restart to activate WSL2 kernel.
echo This installer will resume automatically after you log back in as Admin.
echo ============================================================================
echo.
pause
shutdown /r /t 3
exit /b
:PHASE1_DONE
if exist "%TEMP%\dts_wsl_rebooted.flag" del /f /q "%TEMP%\dts_wsl_rebooted.flag" >nul 2>&1
:: ============================================================================ :: ============================================================================
:: PHASE 2: INITIALIZE UBUNTU USER & ENABLE SYSTEMD IN WSL2 :: PHASE 2: INITIALIZE UBUNTU USER (WITH PASSWORD), SYSTEMD & VMIDLETIMEOUT
:: ============================================================================ :: ============================================================================
echo [1/7] Initializing Ubuntu-22.04 and enabling systemd... echo [1/7] Initializing %WSL_DISTRO%, configuring Linux user, systemd and VM idle timeout...
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" set "WSL_USER="
set /p WSL_USER="Enter Linux username for WSL [Default: %DEFAULT_WSL_USER%]: "
if "%WSL_USER%"=="" set "WSL_USER=%DEFAULT_WSL_USER%"
if /i "%WSL_USER%"=="root" goto :ERR_WSL_ROOT
set "WSL_PASS="
set /p WSL_PASS="Enter Linux sudo password for '%WSL_USER%' [Default: Dts@2026]: "
if "%WSL_PASS%"=="" set "WSL_PASS=Dts@2026"
powershell -NoProfile -ExecutionPolicy Bypass -Command "$wslCfg = Join-Path $env:USERPROFILE '.wslconfig'; Set-Content -Path $wslCfg -Value \"[wsl2]`r`nvmIdleTimeout=-1\" -Encoding Ascii"
set "STEP1_SH=%TEMP%\dts_step1.sh"
> "%STEP1_SH%" echo set -e
>> "%STEP1_SH%" echo WSL_USR="$1"
>> "%STEP1_SH%" echo WSL_PWD="$2"
>> "%STEP1_SH%" echo id -u "$WSL_USR" ^>/dev/null 2^>^&1 ^|^| useradd -m -s /bin/bash -G sudo "$WSL_USR"
>> "%STEP1_SH%" echo echo "${WSL_USR}:${WSL_PWD}" ^| chpasswd
>> "%STEP1_SH%" echo rm -f "/etc/sudoers.d/${WSL_USR}"
>> "%STEP1_SH%" echo printf '[user]\ndefault=%%s\n[boot]\nsystemd=true\n' "$WSL_USR" ^> /etc/wsl.conf
for /f "delims=" %%i in ('wsl -d %WSL_DISTRO% -u root wslpath -a "%STEP1_SH%"') do set "WSL_STEP1_SH=%%i"
wsl -d %WSL_DISTRO% -u root bash -c "tr -d '\r' < '%WSL_STEP1_SH%' > /tmp/dts_step1.sh && bash /tmp/dts_step1.sh '%WSL_USER%' '%WSL_PASS%'; RC=$?; rm -f /tmp/dts_step1.sh; exit $RC"
set "STEP1_ERR=%errorLevel%"
del /f /q "%STEP1_SH%" >nul 2>&1
if %STEP1_ERR% neq 0 goto :ERR_WSL_USER
wsl --terminate %WSL_DISTRO% >nul 2>&1 wsl --terminate %WSL_DISTRO% >nul 2>&1
timeout /t 2 /nobreak >nul timeout /t 3 /nobreak >nul
wsl -d %WSL_DISTRO% -u root bash -c "for i in 1 2 3 4 5 6 7 8 9 10; do systemctl is-system-running >/dev/null 2>&1 && break || sleep 1; done" >nul 2>&1
goto :PHASE2_DONE
:ERR_WSL_ROOT
echo [ERROR] Cannot use root as the standard WSL user!
pause
exit /b 1
:ERR_WSL_USER
echo [ERROR] Failed to create or configure Linux user "%WSL_USER%".
pause
exit /b 1
:PHASE2_DONE
:: ============================================================================ :: ============================================================================
:: 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)... echo [2/7] Installing Docker Engine (%DOCKER_VERSION%) + Compose V2...
wsl -d %WSL_DISTRO% -u root bash -c "echo c2V0IC1lCmlmICEgY29tbWFuZCAtdiBkb2NrZXIgPi9kZXYvbnVsbCAyPiYxOyB0aGVuCiAgYXB0LWdldCB1cGRhdGUKICBhcHQtZ2V0IGluc3RhbGwgLXkgY2EtY2VydGlmaWNhdGVzIGN1cmwgZ251cGcgbHNiLXJlbGVhc2UKICBpbnN0YWxsIC1tIDA3NTUgLWQgL2V0Yy9hcHQva2V5cmluZ3MKICBjdXJsIC1mc1NMIGh0dHBzOi8vZG93bmxvYWQuZG9ja2VyLmNvbS9saW51eC91YnVudHUvZ3BnIHwgZ3BnIC0tZGVhcm1vciAtLXllcyAtbyAvZXRjL2FwdC9rZXlyaW5ncy9kb2NrZXIuZ3BnCiAgZWNobyAiZGViIFthcmNoPSQoZHBrZyAtLXByaW50LWFyY2hpdGVjdHVyZSkgc2lnbmVkLWJ5PS9ldGMvYXB0L2tleXJpbmdzL2RvY2tlci5ncGddIGh0dHBzOi8vZG93bmxvYWQuZG9ja2VyLmNvbS9saW51eC91YnVudHUgJChsc2JfcmVsZWFzZSAtY3MpIHN0YWJsZSIgPiAvZXRjL2FwdC9zb3VyY2VzLmxpc3QuZC9kb2NrZXIubGlzdAogIGFwdC1nZXQgdXBkYXRlCiAgYXB0LWdldCBpbnN0YWxsIC15IGRvY2tlci1jZT01OjI4LjMuMi0xfnVidW50dS4yMi4wNH5qYW1teSBkb2NrZXItY2UtY2xpPTU6MjguMy4yLTF+dWJ1bnR1LjIyLjA0fmphbW15IGNvbnRhaW5lcmQuaW8gZG9ja2VyLWNvbXBvc2UtcGx1Z2luCiAgYXB0LW1hcmsgaG9sZCBkb2NrZXItY2UgZG9ja2VyLWNlLWNsaSBjb250YWluZXJkLmlvCmZpCnN5c3RlbWN0bCBlbmFibGUgZG9ja2VyCnN5c3RlbWN0bCBzdGFydCBkb2NrZXIKdXNlcm1vZCAtYUcgZG9ja2VyIGR0c2FkbWluCg== | base64 -d | bash"
if %errorLevel% neq 0 ( set "STEP2_SH=%TEMP%\dts_step2.sh"
echo [ERROR] Docker installation or startup failed inside WSL. > "%STEP2_SH%" echo set -e
pause >> "%STEP2_SH%" echo DOCKER_VER="$1"
exit /b 1 >> "%STEP2_SH%" echo WSL_USR="$2"
) >> "%STEP2_SH%" echo install_docker() {
>> "%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 }
>> "%STEP2_SH%" echo command -v docker ^>/dev/null 2^>^&1 ^|^| install_docker
>> "%STEP2_SH%" echo systemctl daemon-reload ^>/dev/null 2^>^&1 ^|^| true
>> "%STEP2_SH%" echo systemctl enable docker ^>/dev/null 2^>^&1 ^|^| true
>> "%STEP2_SH%" echo systemctl start docker ^|^| service docker start
>> "%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 goto :ERR_DOCKER_STEP2
goto :PHASE3_DONE
:ERR_DOCKER_STEP2
echo [ERROR] Docker installation or startup failed inside WSL.
pause
exit /b 1
:PHASE3_DONE
:: ============================================================================ :: ============================================================================
:: 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:
set /a LOGIN_ATTEMPT=0
set /a LOGIN_MAX=5
:DOCKER_LOGIN_LOOP
set /a LOGIN_ATTEMPT+=1
echo Please log in to Docker registry (%REGISTRY_URL%) [Attempt %LOGIN_ATTEMPT%/%LOGIN_MAX%]:
wsl -d %WSL_DISTRO% -u root docker login %REGISTRY_URL% wsl -d %WSL_DISTRO% -u root docker login %REGISTRY_URL%
if %errorLevel% neq 0 ( if %errorLevel% equ 0 goto :DOCKER_LOGIN_OK
echo [ERROR] Docker registry login failed.
pause if %LOGIN_ATTEMPT% geq %LOGIN_MAX% goto :DOCKER_LOGIN_FAIL
exit /b 1 echo [WARNING] Docker registry login failed. Please check your username/password and try again...
) echo.
goto :DOCKER_LOGIN_LOOP
:DOCKER_LOGIN_FAIL
echo [ERROR] Docker registry login failed after %LOGIN_MAX% attempts.
pause
exit /b 1
:DOCKER_LOGIN_OK
echo - Docker registry login succeeded!
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" 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" set "STEP3_SH=%TEMP%\dts_step3.sh"
if %errorLevel% neq 0 ( > "%STEP3_SH%" echo set -e
echo [ERROR] Failed to start Docker containers. >> "%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 pause
exit /b 1 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 :: PHASE 5: INTERACTIVE KIOSK USER CREATION & AUTO-LOGON SETUP
:: ============================================================================ :: ============================================================================
@@ -197,26 +350,65 @@ if /i "%PREV_KIOSK_USER%"=="Administrator" goto :SKIP_REMOVE_OLD
echo - Removing previous Kiosk user "%PREV_KIOSK_USER%" and its profile... 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 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 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 :SKIP_REMOVE_OLD
net accounts /minpwlen:0 >nul 2>&1 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 } }" powershell -NoProfile -ExecutionPolicy Bypass -Command ^
wmic useraccount where name="%KIOSK_USER%" set PasswordExpires=False >nul 2>&1 "$u = '%KIOSK_USER%';" ^
net user "%KIOSK_USER%" /logonpasswordchg:no >nul 2>&1 "$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 ( if %errorLevel% neq 0 (
echo [ERROR] Failed to create or update user "%KIOSK_USER%". echo [ERROR] Failed to create or update user "%KIOSK_USER%".
pause pause
exit /b 1 exit /b 1
) )
echo [6/7] Applying Kiosk Shell, Auto-Logon and Persistent Browser Profile... 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, WSL Boot Task and Browser Profile...
if not exist "%KIOSK_DATA_DIR%" mkdir "%KIOSK_DATA_DIR%" if not exist "%KIOSK_DATA_DIR%" mkdir "%KIOSK_DATA_DIR%"
if not exist "%KIOSK_APP_DIR%" mkdir "%KIOSK_APP_DIR%" if not exist "%KIOSK_APP_DIR%" mkdir "%KIOSK_APP_DIR%"
copy /Y "%ROOT_DIR%templates\startup.html" "%KIOSK_APP_DIR%\startup.html" >nul copy /Y "%ROOT_DIR%templates\startup.html" "%KIOSK_APP_DIR%\startup.html" >nul
icacls "%KIOSK_DATA_DIR%" /grant "%KIOSK_USER%:(OI)(CI)F" /T >nul icacls "%KIOSK_DATA_DIR%" /grant "%KIOSK_USER%:(OI)(CI)F" /T >nul
icacls "%KIOSK_APP_DIR%" /grant "Users:(OI)(CI)RX" /T >nul icacls "%KIOSK_APP_DIR%" /grant "Users:(OI)(CI)RX" /T >nul
:: Create WSL2 + Docker 24/7 Auto-Start Script and System Startup Task
> "%KIOSK_APP_DIR%\start_wsl_docker.bat" echo @echo off
>> "%KIOSK_APP_DIR%\start_wsl_docker.bat" echo wsl -d %WSL_DISTRO% -u root bash -c "systemctl is-active --quiet docker || service docker start; cd '%PROJECT_DIR%' && docker compose -p '%PROJECT_NAME%' up -d"
>> "%KIOSK_APP_DIR%\start_wsl_docker.bat" echo start "" /b wsl -d %WSL_DISTRO% -u root sleep infinity
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
"$u = \"$env:USERDOMAIN\$env:USERNAME\";" ^
"$act = New-ScheduledTaskAction -Execute '%KIOSK_APP_DIR%\start_wsl_docker.bat';" ^
"$trig = New-ScheduledTaskTrigger -AtStartup;" ^
"$prin = New-ScheduledTaskPrincipal -UserId $u -LogonType S4U -RunLevel Highest;" ^
"$set = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 5 -RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew;" ^
"Register-ScheduledTask -TaskName 'WSL Docker Startup' -Action $act -Trigger $trig -Principal $prin -Settings $set -Force | Out-Null"
if %errorLevel% neq 0 (
echo [WARNING] Failed to create Task Scheduler entry WSL Docker Startup!
) else (
echo - Registered 24/7 startup task: WSL Docker Startup (User: %USERDOMAIN%\%USERNAME%)
)
set "WINLOGON_KEY=HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" set "WINLOGON_KEY=HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
reg add "%WINLOGON_KEY%" /v "AutoAdminLogon" /t REG_SZ /d "1" /f >nul reg add "%WINLOGON_KEY%" /v "AutoAdminLogon" /t REG_SZ /d "1" /f >nul
reg add "%WINLOGON_KEY%" /v "DefaultDomainName" /t REG_SZ /d "%COMPUTERNAME%" /f >nul reg add "%WINLOGON_KEY%" /v "DefaultDomainName" /t REG_SZ /d "%COMPUTERNAME%" /f >nul
@@ -231,19 +423,72 @@ 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 "ClearBrowsingDataOnExit" /t REG_DWORD /d 0 /f >nul
reg add "%EDGE_POL%" /v "RestoreOnStartup" /t REG_DWORD /d 4 /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 schtasks /delete /tn "DTS_Torque_Vault_Kiosk" /f >nul 2>&1
:: ============================================================================ :: ============================================================================
:: PHASE 6: CONFIGURE 24/7 ALWAYS-ON POWER PLAN & BLOCK AUTO-REBOOT UPDATES :: PHASE 6: CONFIGURE 24/7 ALWAYS-ON POWER PLAN & BLOCK AUTO-REBOOT UPDATES
:: ============================================================================ :: ============================================================================
echo [7/7] Configuring 24/7 Always-On Power Plan and blocking Windows Update auto-reboots... echo.
echo [7/7] Configuring 24/7 Power Plan and blocking Windows Update auto-reboots...
:ASK_DISPLAY_TIMEOUT
if "%DEFAULT_DISPLAY_OFF_MINUTES%"=="" set "DEFAULT_DISPLAY_OFF_MINUTES=15"
set "DISPLAY_OFF_MINUTES="
set /p DISPLAY_OFF_MINUTES="Enter display off timeout in minutes (0 = Always On) [Default: %DEFAULT_DISPLAY_OFF_MINUTES%]: "
if "%DISPLAY_OFF_MINUTES%"=="" set "DISPLAY_OFF_MINUTES=%DEFAULT_DISPLAY_OFF_MINUTES%"
powershell -NoProfile -Command "if ('%DISPLAY_OFF_MINUTES%' -match '^\d+$') { exit 0 } else { exit 1 }"
if %errorLevel% neq 0 goto :INVALID_DISPLAY_TIMEOUT
goto :VALID_DISPLAY_TIMEOUT
:INVALID_DISPLAY_TIMEOUT
echo [WARNING] Invalid number - enter 0 or a positive integer such as 15.
goto :ASK_DISPLAY_TIMEOUT
:VALID_DISPLAY_TIMEOUT
if "%DISPLAY_OFF_MINUTES%"=="0" set "DISPLAY_STATUS_MSG=Always On (0m)"
if not "%DISPLAY_OFF_MINUTES%"=="0" set "DISPLAY_STATUS_MSG=Display off %DISPLAY_OFF_MINUTES%m"
echo - Applying Power Plan (%DISPLAY_STATUS_MSG%, No Lock/Sleep)...
powercfg -setactive 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c >nul 2>&1 powercfg -setactive 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c >nul 2>&1
powercfg -h off >nul 2>&1 powercfg -h off >nul 2>&1
powercfg -change -monitor-timeout-ac 0 >nul :: Allow display to turn off after DISPLAY_OFF_MINUTES (0 = Never) while CPU/WSL/Docker stay 100% awake
powercfg -change -monitor-timeout-dc 0 >nul powercfg -change -monitor-timeout-ac %DISPLAY_OFF_MINUTES% >nul
powercfg -change -monitor-timeout-dc %DISPLAY_OFF_MINUTES% >nul
:: Keep system, hibernate, and disk strictly Always-On (0 = Never)
powercfg -change -standby-timeout-ac 0 >nul powercfg -change -standby-timeout-ac 0 >nul
powercfg -change -standby-timeout-dc 0 >nul powercfg -change -standby-timeout-dc 0 >nul
powercfg -change -hibernate-timeout-ac 0 >nul powercfg -change -hibernate-timeout-ac 0 >nul
@@ -251,8 +496,16 @@ powercfg -change -hibernate-timeout-dc 0 >nul
powercfg -change -disk-timeout-ac 0 >nul powercfg -change -disk-timeout-ac 0 >nul
powercfg -change -disk-timeout-dc 0 >nul powercfg -change -disk-timeout-dc 0 >nul
:: Disable USB Selective Suspend so touchscreen/peripherals wake display immediately
powercfg -setacvalueindex SCHEME_CURRENT 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 0 >nul 2>&1 powercfg -setacvalueindex SCHEME_CURRENT 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 0 >nul 2>&1
powercfg -setdcvalueindex SCHEME_CURRENT 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 0 >nul 2>&1 powercfg -setdcvalueindex SCHEME_CURRENT 2a737441-1930-4402-8d77-b2bebba308a3 48e6b7a6-50f5-4782-a5d4-53bb8f07e226 0 >nul 2>&1
:: Prevent Windows from locking Kiosk session when display turns off
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\7516b95f-f776-4464-8c53-06167f40cc99\8ec4b3a5-6868-48c2-be75-4f3044be88a7" /v "Attributes" /t REG_DWORD /d 2 /f >nul
powercfg -setacvalueindex SCHEME_CURRENT 7516b95f-f776-4464-8c53-06167f40cc99 8ec4b3a5-6868-48c2-be75-4f3044be88a7 0 >nul 2>&1
powercfg -setdcvalueindex SCHEME_CURRENT 7516b95f-f776-4464-8c53-06167f40cc99 8ec4b3a5-6868-48c2-be75-4f3044be88a7 0 >nul 2>&1
reg add "HKCU\Control Panel\Desktop" /v "ScreenSaveActive" /t REG_SZ /d "0" /f >nul
reg add "HKCU\Control Panel\Desktop" /v "ScreenSaverIsSecure" /t REG_SZ /d "0" /f >nul
powercfg -setactive SCHEME_CURRENT >nul 2>&1 powercfg -setactive SCHEME_CURRENT >nul 2>&1
reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" /v "NoAutoRebootWithLoggedOnUsers" /t REG_DWORD /d 1 /f >nul reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" /v "NoAutoRebootWithLoggedOnUsers" /t REG_DWORD /d 1 /f >nul
@@ -261,12 +514,13 @@ reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" /v "AUOption
echo. echo.
echo ============================================================================ echo ============================================================================
echo ALL-IN-ONE 24/7 KIOSK DEPLOYMENT COMPLETED! echo ALL-IN-ONE 24/7 KIOSK DEPLOYMENT COMPLETED!
echo - WSL2 + Docker 28.3.2 : Installed and Auto-Starting at Boot echo - WSL2 + Docker : %DOCKER_VERSION% (User: %WSL_USER%, Task: WSL Docker Startup)
echo - Walmart Containers : Running in %PROJECT_DIR% echo - Walmart Containers : Online and Verified on Port %HEALTH_PORT% in %PROJECT_DIR%
echo - Kiosk User : %KIOSK_USER% (Auto-Logon + Persistent Data) echo - Kiosk User : %KIOSK_USER% (Auto-Logon + Persistent Data)
echo - Power and Updates : 24/7 Always-On (No Sleep / No Auto-Reboot) echo - Power and Updates : 24/7 Always-On (%DISPLAY_STATUS_MSG%, No Lock/Sleep)
echo ============================================================================ echo ============================================================================
echo. echo.
set "REBOOT_FINAL="
set /p REBOOT_FINAL="Reboot now to enter full Kiosk Production mode? (Y/N): " set /p REBOOT_FINAL="Reboot now to enter full Kiosk Production mode? (Y/N): "
if /i "%REBOOT_FINAL%"=="Y" shutdown /r /t 3 if /i "%REBOOT_FINAL%"=="Y" shutdown /r /t 3
pause pause
-34
View File
@@ -1,34 +0,0 @@
@echo off
setlocal
:: ============================================================================
:: CONFIGURATION
:: ============================================================================
set "GITEA_URL=https://gitea.digitoolsolutions.synology.me"
set "REPO_OWNER=lamtruong28"
set "REPO_NAME=mini-pc-setup"
:: ============================================================================
:: AUTO-ELEVATE TO ADMINISTRATOR
:: ============================================================================
net session >nul 2>&1
if %errorLevel% neq 0 (
echo Requesting Administrator privileges...
powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
exit /b
)
echo ============================================================================
echo DTS TORQUE VAULT - ONE-CLICK LATEST RELEASE BOOTSTRAPPER
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"
if %errorLevel% neq 0 (
echo.
echo [ERROR] Bootstrap failed. Verify that at least one Release exists on Gitea.
pause
exit /b 1
)
+119 -22
View File
@@ -2,9 +2,17 @@
setlocal EnableDelayedExpansion 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 "WSL_DISTRO=Ubuntu-22.04"
set "PROJECT_NAME=walmart"
set "PROJECT_DIR=/opt/walmart" set "PROJECT_DIR=/opt/walmart"
set "KIOSK_APP_DIR=C:\KioskApp" set "KIOSK_APP_DIR=C:\KioskApp"
set "KIOSK_DATA_DIR=C:\KioskBrowserData" set "KIOSK_DATA_DIR=C:\KioskBrowserData"
@@ -23,19 +31,41 @@ echo ===========================================================================
echo DTS TORQUE VAULT - KIOSK MODE UNINSTALLER AND SYSTEM RESTORE echo DTS TORQUE VAULT - KIOSK MODE UNINSTALLER AND SYSTEM RESTORE
echo ============================================================================ echo ============================================================================
echo. echo.
echo This tool will: echo Select uninstall mode:
echo 1. Disable Windows Auto-Logon and Kiosk Shell restrictions echo [1] Auto Wipe All - Automatically remove Kiosk user, browser data,
echo 2. Remove or restore the dedicated Kiosk user account echo scheduled tasks, Docker containers, database volumes
echo 3. Remove startup tasks and restore default Power / Update policies echo and the '%ROOT_FOLDER_NAME%' setup folder
echo 4. Optionally stop and remove Walmart Docker containers echo [2] Manual / Custom - Choose step-by-step what to keep or delete
echo [0] Cancel
echo. echo.
set /p CONFIRM="Are you sure you want to uninstall Kiosk Mode? (Y/N): " set "UNINSTALL_MODE="
if /i not "%CONFIRM%"=="Y" ( set /p UNINSTALL_MODE="Enter your choice [1 / 2 / 0]: "
if "%UNINSTALL_MODE%"=="0" (
echo Uninstall cancelled. echo Uninstall cancelled.
pause pause
exit /b 0 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 :: 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 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 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" ( 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. echo - Removed Kiosk user "%KIOSK_USER%" and its local profile.
) else ( ) 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 } } }" powershell -NoProfile -ExecutionPolicy Bypass -Command ^
echo - Restored normal Windows Desktop shell for "%KIOSK_USER%". "$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 goto :AFTER_KIOSK_USER
@@ -89,17 +150,22 @@ echo - No separate Kiosk user account needed removal.
:: 3. REMOVE SCHEDULED TASKS AND KIOSK LOCAL FILES :: 3. REMOVE SCHEDULED TASKS AND KIOSK LOCAL FILES
:: ============================================================================ :: ============================================================================
echo [3/5] Removing scheduled tasks and local Kiosk app files... echo [3/5] Removing scheduled tasks and local Kiosk app files...
schtasks /delete /tn "DTS_WSL_Docker_AutoStart" /f >nul 2>&1 schtasks /delete /tn "WSL Docker Startup" /f >nul 2>&1
schtasks /delete /tn "DTS_Torque_Vault_Kiosk" /f >nul 2>&1 schtasks /delete /tn "DTS_Torque_Vault_Kiosk" /f >nul 2>&1
reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v "DTS_Master_Setup" /f >nul 2>&1 reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v "DTS_Master_Setup" /f >nul 2>&1
if exist "%KIOSK_APP_DIR%" rmdir /s /q "%KIOSK_APP_DIR%" >nul 2>&1 if exist "%KIOSK_APP_DIR%" rmdir /s /q "%KIOSK_APP_DIR%" >nul 2>&1
if exist "%KIOSK_DATA_DIR%" ( 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" ( if /i "!DEL_BROWSER!"=="Y" (
rmdir /s /q "%KIOSK_DATA_DIR%" >nul 2>&1 rmdir /s /q "%KIOSK_DATA_DIR%" >nul 2>&1
echo - Removed %KIOSK_DATA_DIR% 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 "NoAutoRebootWithLoggedOnUsers" /f >nul 2>&1
reg delete "HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" /v "AUOptions" /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... echo [5/5] Checking WSL Docker containers...
wsl -d %WSL_DISTRO% -u root true >nul 2>&1 wsl -d %WSL_DISTRO% -u root true >nul 2>&1
if %errorLevel% neq 0 goto :UNINSTALL_DONE if %errorLevel% neq 0 goto :UNINSTALL_DONE
set "STOP_DOCKER=" set "STOP_DOCKER=Y"
set /p STOP_DOCKER="Stop and remove Walmart Docker containers in %PROJECT_DIR%? (Y/N): " 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 if /i not "%STOP_DOCKER%"=="Y" goto :UNINSTALL_DONE
set "DEL_VOLUMES=" set "DEL_VOLUMES=Y"
set /p DEL_VOLUMES="Also delete database volumes - WARNING deletes all local data? (Y/N): " if "%AUTO_WIPE%"=="0" (
set /p DEL_VOLUMES="Also delete database volumes - WARNING deletes all local data? (Y/N): "
)
if /i "%DEL_VOLUMES%"=="Y" ( 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%" 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, volumes, and %PROJECT_DIR%. echo - Removed containers, database volumes, and %PROJECT_DIR%.
) else ( ) 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. echo - Stopped and removed containers - database volumes preserved.
) )
:UNINSTALL_DONE :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 ============================================================================ echo ============================================================================
echo UNINSTALL COMPLETED! 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 - Normal Windows Desktop and Power/Update policies restored
echo ============================================================================ echo ============================================================================
echo. echo.
set "REBOOT_NOW=" set "REBOOT_NOW="
set /p REBOOT_NOW="Reboot now to apply all changes cleanly? (Y/N): " 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 if /i "%REBOOT_NOW%"=="Y" shutdown /r /t 3
pause pause
+99 -52
View File
@@ -2,15 +2,25 @@
setlocal EnableDelayedExpansion setlocal EnableDelayedExpansion
:: ============================================================================ :: ============================================================================
:: CONFIGURATION (RESOLVE PARENT ROOT DIRECTORY FROM /scripts) :: CONFIGURATION (SYNCED WITH INSTALL.BAT & UNINSTALL.BAT)
:: ============================================================================ :: ============================================================================
set "SCRIPT_DIR=%~dp0" set "SCRIPT_DIR=%~dp0"
for %%I in ("%SCRIPT_DIR%..") do set "ROOT_DIR=%%~fI\" for %%I in ("%SCRIPT_DIR%..") do set "ROOT_DIR=%%~fI\"
set "CLEAN_ROOT=%ROOT_DIR:~0,-1%" set "CLEAN_ROOT=%ROOT_DIR:~0,-1%"
:: WSL2 & Project Settings
set "WSL_DISTRO=Ubuntu-22.04" set "WSL_DISTRO=Ubuntu-22.04"
set "PROJECT_NAME=walmart"
set "PROJECT_DIR=/opt/walmart" set "PROJECT_DIR=/opt/walmart"
set "REGISTRY_URL=gitea.digitoolsolutions.synology.me" 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" set "KIOSK_APP_DIR=C:\KioskApp"
:: ============================================================================ :: ============================================================================
@@ -24,13 +34,34 @@ if %errorLevel% neq 0 (
) )
echo ============================================================================ echo ============================================================================
echo DTS TORQUE VAULT - SYSTEM UPDATE (CONTAINERS AND KIOSK SHELL) echo DTS TORQUE VAULT - PRODUCTION UPDATE MANAGER (ZERO-BASE64 EDITION)
echo ============================================================================ echo ============================================================================
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 ping -n 1 8.8.8.8 >nul 2>&1
if %errorLevel% neq 0 ( if %errorLevel% neq 0 (
echo [ERROR] No Internet connection detected! Connect LAN/Wi-Fi and run again. echo [ERROR] No Internet connection detected! Connect LAN/Wi-Fi and run again.
@@ -38,74 +69,90 @@ if %errorLevel% neq 0 (
exit /b 1 exit /b 1
) )
wsl -d %WSL_DISTRO% -u root true >nul 2>&1 :: ============================================================================
if %errorLevel% neq 0 ( :: 2. SYNC KIOSK STARTUP TEMPLATE & AUTHENTICATE REGISTRY
echo [ERROR] WSL distribution "%WSL_DISTRO%" is not installed. Run install.bat first. :: ============================================================================
pause echo [2/4] Updating Kiosk startup screen and checking Docker registry login...
exit /b 1
)
:: ============================================================================
:: 2. UPDATE KIOSK STARTUP PAGE (IF PRESENT)
:: ============================================================================
echo [1/4] Updating Kiosk startup template...
if exist "%ROOT_DIR%templates\startup.html" ( if exist "%ROOT_DIR%templates\startup.html" (
if not exist "%KIOSK_APP_DIR%" mkdir "%KIOSK_APP_DIR%" if not exist "%KIOSK_APP_DIR%" mkdir "%KIOSK_APP_DIR%"
copy /Y "%ROOT_DIR%templates\startup.html" "%KIOSK_APP_DIR%\startup.html" >nul 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 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% wsl -d %WSL_DISTRO% -u root docker login %REGISTRY_URL%
if %errorLevel% neq 0 ( if %errorLevel% neq 0 (
echo [ERROR] Docker registry login failed. echo [ERROR] Docker registry login failed for %REGISTRY_URL%.
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.
pause pause
exit /b 1 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... echo [3/4] Pulling latest images, updating containers, and verifying Online status...
wsl -d %WSL_DISTRO% -u root docker image prune -f >nul 2>&1
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 ============================================================================ echo ============================================================================
echo UPDATE COMPLETED SUCCESSFULLY! echo UPDATE COMPLETED SUCCESSFULLY!
echo - All containers are up to date and running in %PROJECT_DIR% echo - Project / Directory : %PROJECT_NAME% (%PROJECT_DIR%)
echo - Database and Kiosk user configuration were preserved echo - Backend Health : Verified Online on Port %HEALTH_PORT%
echo - Database Volumes : Preserved safely
echo ============================================================================ echo ============================================================================
echo. echo.
pause pause
+69
View File
@@ -0,0 +1,69 @@
@echo off
setlocal EnableDelayedExpansion
:: ============================================================================
:: CONFIGURATION
:: ============================================================================
set "GITEA_URL=https://gitea.digitoolsolutions.synology.me"
set "REPO_OWNER=lamtruong28"
set "REPO_NAME=mini-pc-setup"
set "EXTRACT_DIR=C:\Apps\%REPO_NAME%"
:: ============================================================================
:: 0. AUTO-ELEVATE TO ADMINISTRATOR
:: ============================================================================
net session >nul 2>&1
if %errorLevel% neq 0 (
echo Requesting Administrator privileges...
powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
exit /b
)
echo ============================================================================
echo DTS TORQUE VAULT - ONE-CLICK LATEST RELEASE BOOTSTRAPPER
echo ============================================================================
echo Repository : %GITEA_URL%/%REPO_OWNER%/%REPO_NAME%
echo Destination : %EXTRACT_DIR%
echo.
:: ============================================================================
:: 1. PRE-CHECK DNS & INTERNET CONNECTIVITY
:: ============================================================================
echo [1/3] Checking network and DNS resolution for %GITEA_URL%...
powershell -NoProfile -ExecutionPolicy Bypass -Command "$h=([System.Uri]'%GITEA_URL%').Host; try { [System.Net.Dns]::GetHostAddresses($h) | Out-Null; exit 0 } catch { Write-Host '[ERROR] Cannot resolve DNS for' $h '- Check Internet.' -ForegroundColor Red; exit 1 }"
if %errorLevel% neq 0 (
pause
exit /b 1
)
:: ============================================================================
:: 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 "$tmp = Join-Path $env:TEMP 'dts_release_extract'; if (Test-Path $tmp) { Remove-Item $tmp -Recurse -Force }; Expand-Archive -Path '%ZIP_FILE%' -DestinationPath $tmp -Force; $inner = Get-ChildItem -Path $tmp -Directory | Select-Object -First 1; if ($inner) { Get-ChildItem -Path $inner.FullName -Force | Copy-Item -Destination '%EXTRACT_DIR%' -Recurse -Force } else { Get-ChildItem -Path $tmp -Force | Copy-Item -Destination '%EXTRACT_DIR%' -Recurse -Force }; Remove-Item $tmp -Recurse -Force; Remove-Item '%ZIP_FILE%' -Force"
if not exist "%EXTRACT_DIR%\scripts\install.bat" (
echo [ERROR] scripts\install.bat not found inside %EXTRACT_DIR%!
pause
exit /b 1
)
call "%EXTRACT_DIR%\scripts\install.bat"