<# .SYNOPSIS Deploys a new build to the live publish tree and restarts ZKTecoSyncService. .DESCRIPTION Ordering rule learned the hard way on 2026-10-11 23:27: this script MUST NOT be able to leave the host down. The previous version called Stop-Service, then copied immediately. Stop-Service returned while the host process was still alive and holding AttendanceHub.Sync.dll, the copy threw "file in use", $ErrorActionPreference = 'Stop' terminated the script, and the service was left Stopped with nothing deployed and nobody watching. Capture was down until someone noticed. So the script now: 1. stops the service, then waits for the PROCESS to actually exit 2. force-kills the orphan if it refuses to leave 3. copies with retries (a file can stay mapped briefly after exit) 4. starts the service in a finally block, so a copy failure still restores it 5. verifies the service is Running and prints what it shipped Everything below runs elevated: stopping/starting a service needs admin rights. #> [CmdletBinding()] param( # Run without the trailing "Press Enter to close", so the script can be driven # by a deployment job rather than a human at a console. Without this an # elevated, automated run hangs forever waiting for a keypress. [switch]$NonInteractive, # Write a full transcript here. Required for unattended runs: Start-Process # refuses to combine -Verb RunAs with -RedirectStandardOutput, so an elevated # run would otherwise leave no readable record of what it did. [string]$OutputLog ) $ErrorActionPreference = 'Stop' if ($OutputLog) { Start-Transcript -Path $OutputLog -Force | Out-Null } $p = 'G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\publish' $s = 'G:\WEB-SERVER\htdocs\AttendanceHub\ZKTecoSyncService-V2\_build\publish-staging' $svc = 'ZKTecoSyncService' $procName = 'AttendanceHub.Sync.Host' $deployedOk = $false function Wait-HostExit([int]$TimeoutSec) { $deadline = (Get-Date).AddSeconds($TimeoutSec) while ((Get-Date) -lt $deadline) { if (-not (Get-Process -Name $procName -ErrorAction SilentlyContinue)) { return $true } Start-Sleep -Milliseconds 500 } return $false } function Copy-WithRetry([string]$Src, [string]$Dst, [int]$Attempts) { for ($i = 1; $i -le $Attempts; $i++) { try { Copy-Item $Src $Dst -Force return } catch { if ($i -eq $Attempts) { throw } Write-Host (" retry {0}/{1} copying {2}: {3}" -f $i, $Attempts, (Split-Path $Src -Leaf), $_.Exception.Message) Start-Sleep -Seconds 2 } } } try { # ---------- PRE-FLIGHT: would this deploy actually change anything? ---------- # Caught on 2026-10-12 02:4x: `dotnet build` writes to bin\Release, this script copies from # _build\publish-staging, and publish-staging was never re-published. The script stopped the # service, copied byte-identical files, printed sizes, and reported DEPLOY DONE — a full # restart that shipped nothing. Comparing hashes BEFORE stopping the service turns that silent # no-op into a loud refusal, and costs no restart at all. $payload = @('AttendanceHub.Sync.dll', 'AttendanceHub.Sync.Host.dll', 'AttendanceHub.Sync.Host.exe') $unchanged = @() foreach ($f in $payload) { $srcF = Join-Path $s $f $dstF = Join-Path $p $f if (-not (Test-Path $srcF)) { throw "staging is missing $f - publish first (dotnet publish -o $s)" } if ((Test-Path $dstF) -and ((Get-FileHash $srcF).Hash -eq (Get-FileHash $dstF).Hash)) { $unchanged += $f } } if ($unchanged.Count -eq $payload.Count) { Write-Host '' Write-Host 'DEPLOY ABORTED: staging is byte-identical to live.' -ForegroundColor Red Write-Host ' Nothing would change, so the service is NOT being restarted.' -ForegroundColor Yellow Write-Host " Files checked: $($payload -join ', ')" -ForegroundColor Yellow Write-Host ' Most likely cause: the build was not published to staging.' -ForegroundColor Yellow Write-Host " dotnet publish -c Release -o $s" -ForegroundColor Cyan Write-Host ' Then re-run this script.' -ForegroundColor Yellow Write-Host '' if ($OutputLog) { Stop-Transcript | Out-Null } exit 4 } if ($unchanged.Count -gt 0) { Write-Host "PRE-FLIGHT: unchanged in staging (will be copied anyway): $($unchanged -join ', ')" -ForegroundColor Yellow } Write-Host "Stopping $svc ..." try { Stop-Service -Name $svc -Force } catch { Write-Host " stop reported: $($_.Exception.Message)" } # Stop-Service returning is NOT the same as the process being gone. The DLLs stay # locked until the process exits, and on 2026-10-11 it had not exited after 26s. if (Wait-HostExit -TimeoutSec 90) { Write-Host 'Host process exited cleanly.' } else { Write-Host 'Host process did not exit in 90s - force killing the orphan.' Get-Process -Name $procName -ErrorAction SilentlyContinue | Stop-Process -Force [void](Wait-HostExit -TimeoutSec 30) } Write-Host 'Copying new build ...' # The Host project owns the process entry point, the upload loop and (since # 2026-10-11) the delivery watchdog. Copying only AttendanceHub.Sync.dll ships # library changes while silently skipping every Host change, so a deploy could # report success and change nothing observable. Both halves go over together. foreach ($f in @('AttendanceHub.Sync.dll', 'AttendanceHub.Sync.Host.dll', 'AttendanceHub.Sync.Host.exe')) { Copy-WithRetry (Join-Path $s $f) (Join-Path $p $f) 4 Write-Host (" {0} -> {1} bytes" -f $f, (Get-Item (Join-Path $p $f)).Length) } # ---- GUARDED config copy ------------------------------------------------- # The staging tree ships config\phase1.device.json as a TEMPLATE whose # upload.enabled is false (acquisition-only). Publishing that file verbatim # silently turns the uploader off, and every punch then sits Pending forever # with upload_attempts=0, because a disabled uploader never even tries. # That exact incident happened on 2026-10-11 (deploy of 2026-10-10 23:46) # and cost a full morning of un-delivered attendance. # # So: never let a deploy REMOVE delivery. If staging would disable an upload # that is currently enabled, keep the live value and shout about it. $srcCfg = Join-Path $s 'config\phase1.device.json' $dstCfg = Join-Path $p 'config\phase1.device.json' function Get-UploadEnabled([string]$path) { if (-not (Test-Path $path)) { return $null } $raw = [System.IO.File]::ReadAllText($path) $m = [regex]::Match($raw, '("upload"\s*:\s*\{\s*"enabled"\s*:\s*)(true|false)') if (-not $m.Success) { return $null } return ($m.Groups[2].Value -eq 'true') } $stageEnabled = Get-UploadEnabled $srcCfg $liveEnabled = Get-UploadEnabled $dstCfg if ($liveEnabled -eq $true -and $stageEnabled -ne $true) { Write-Host '' Write-Host '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' -ForegroundColor Red Write-Host ' CONFIG GUARD: staging config would DISABLE the uploader.' -ForegroundColor Red Write-Host " live upload.enabled = $liveEnabled" -ForegroundColor Yellow Write-Host " staging upload.enabled = $stageEnabled" -ForegroundColor Yellow Write-Host ' Delivery is being PRESERVED. The template is NOT copied over' -ForegroundColor Yellow Write-Host ' the live config. Fix upload.enabled in the source template,' -ForegroundColor Yellow Write-Host ' or edit publish\config directly and restart the service.' -ForegroundColor Yellow Write-Host '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' -ForegroundColor Red Write-Host '' } else { Copy-WithRetry $srcCfg $dstCfg 2 Write-Host ("config: copied from staging (upload.enabled={0})" -f $stageEnabled) } $deployedOk = $true } finally { # Restoration is unconditional. A failed copy must never leave the host down: # the previous build is still in place and still delivers, so starting it is # always better than staying stopped. Write-Host "Starting $svc ..." try { Start-Service -Name $svc Start-Sleep -Seconds 5 } catch { Write-Host "START FAILED: $($_.Exception.Message)" -ForegroundColor Red } } Write-Host '' Get-Service -Name $svc | Format-Table Name,Status -AutoSize Write-Host ("deployedOk = {0}" -f $deployedOk) foreach ($f in @('AttendanceHub.Sync.dll', 'AttendanceHub.Sync.Host.dll', 'AttendanceHub.Sync.Host.exe')) { $i = Get-Item (Join-Path $p $f) Write-Host (" {0,-30} {1,10} bytes {2}" -f $f, $i.Length, $i.LastWriteTime) } $running = (Get-Service -Name $svc).Status -eq 'Running' if (-not $running) { Write-Host 'DEPLOY FAILED: service is NOT running' -ForegroundColor Red } elseif (-not $deployedOk) { Write-Host 'PARTIAL: service restarted on the OLD build' -ForegroundColor Yellow } else { Write-Host 'DEPLOY DONE' } if (-not $NonInteractive) { Read-Host 'Press Enter to close' } if ($OutputLog) { Stop-Transcript | Out-Null }