<#
.SYNOPSIS
    維修工作階段開關 — 啟用/停用維修帳號(可選的進階安全做法)。
.DESCRIPTION
    若你希望「平時帳號停用、要維修時才開」,可用此腳本切換。
      -Enable  啟用帳號 + (可選) tailscale up
      -Disable 停用帳號 + (可選) tailscale logout
    搭配 config.json 的 EnableAccountOnInstall=false 使用。
.EXAMPLE
    powershell -ExecutionPolicy Bypass -File Set-RepairSession.ps1 -Enable
.EXAMPLE
    powershell -ExecutionPolicy Bypass -File Set-RepairSession.ps1 -Disable -Tailscale
.NOTES
    需以系統管理員身分執行。
#>
[CmdletBinding(DefaultParameterSetName = 'Enable')]
param(
    [Parameter(ParameterSetName = 'Enable')] [switch]$Enable,
    [Parameter(ParameterSetName = 'Disable')] [switch]$Disable,
    [string]$Account,
    # 同時切換 Tailscale 連線
    [switch]$Tailscale
)

$ErrorActionPreference = 'Stop'
$TailscaleExe = Join-Path $env:ProgramFiles 'Tailscale\tailscale.exe'
$StateFile = Join-Path $env:ProgramData 'AIRemoteRepair\state.json'

# Fall back to PATH if Tailscale isn't at the default Program Files location (32-bit host,
# non-default install), so a requested -Tailscale toggle isn't silently skipped below.
if (-not (Test-Path $TailscaleExe)) {
    $cmd = Get-Command tailscale.exe -ErrorAction SilentlyContinue
    if ($cmd) { $TailscaleExe = $cmd.Source }
}

# 找出帳號名稱
if (-not $Account) {
    if (Test-Path $StateFile) {
        try { $Account = (Get-Content $StateFile -Raw | ConvertFrom-Json).RepairAccountName } catch {}
    }
    if (-not $Account) { $Account = 'svc-vendor-repair' }
}

$id = [Security.Principal.WindowsIdentity]::GetCurrent()
if (-not (New-Object Security.Principal.WindowsPrincipal($id)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    throw '必須以系統管理員身分執行。'
}

if ($Enable) {
    Enable-LocalUser -Name $Account
    Write-Host "[OK] 已啟用帳號:$Account" -ForegroundColor Green
    if ($Tailscale) {
        if (Test-Path $TailscaleExe) {
            & $TailscaleExe up --unattended
            Write-Host "[OK] Tailscale 已連線。IP=$(& $TailscaleExe ip -4)" -ForegroundColor Green
        }
        else { Write-Warning "已要求 -Tailscale 但找不到 tailscale.exe;已略過 Tailscale 連線切換。" }
    }
}
elseif ($Disable) {
    Disable-LocalUser -Name $Account
    Write-Host "[OK] 已停用帳號:$Account(注意:不會中斷已連線的工作階段)" -ForegroundColor Yellow
    if ($Tailscale) {
        if (Test-Path $TailscaleExe) {
            & $TailscaleExe logout
            Write-Host '[OK] Tailscale 已登出。' -ForegroundColor Yellow
        }
        else { Write-Warning "已要求 -Tailscale 但找不到 tailscale.exe;已略過 Tailscale 登出。" }
    }
}
else {
    Write-Host '請指定 -Enable 或 -Disable。' -ForegroundColor Red
    exit 1
}
