# BooControl forced-command wrapper (sam-desktop / Windows).
#
# Bound to the BooControl SSH key via authorized_keys:
#   command="powershell -NoProfile -ExecutionPolicy Bypass -File D:\llama-swap\boocontrol-edit.ps1",restrict ssh-ed25519 AAAA... boocontrol@sam-desktop
#
# The key can do NOTHING but the verbs below, all hardcoded to D:\llama-swap and
# D:\models. The only client-supplied value is the HF repo id, regex-validated.
# Place this file at D:\llama-swap\boocontrol-edit.ps1.

$ErrorActionPreference = 'Stop'
$cfg     = 'D:\llama-swap\config.yaml'
$models  = 'D:\models'
$service = 'llama-swap'   # nssm service name

$cmd = $env:SSH_ORIGINAL_COMMAND
if ($null -eq $cmd) { $cmd = '' }
$parts = $cmd -split ' ', 2
$verb  = $parts[0]
$arg   = if ($parts.Count -gt 1) { $parts[1].Trim() } else { '' }

switch ($verb) {
  'read' {
    if (Test-Path $cfg) { Get-Content -Raw $cfg } else { '' }
  }
  'backup' {
    $stamp = Get-Date -Format 'yyyyMMddTHHmmssZ'
    Copy-Item $cfg "$cfg.bak-$stamp"
    Write-Output "$cfg.bak-$stamp"
  }
  'write' {
    $in = [Console]::In.ReadToEnd()
    Set-Content -Path $cfg -Value $in -NoNewline
  }
  'restart' {
    nssm restart $service
  }
  'pull' {
    if ($arg -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*$') {
      Write-Error "bad repo id: $arg"; exit 1
    }
    $dest = Join-Path $models ($arg -replace '/', '__')
    # arg is regex-validated to org/name with no spaces/metacharacters.
    huggingface-cli download $arg --local-dir $dest
  }
  default {
    Write-Error "denied: $verb"; exit 1
  }
}
