<#
  Runs ON the IIS server (invoked over SSH by scripts\run-migrations-remote.ps1). Not meant
  to be run by hand except for troubleshooting.

  Applies pending migrations to the live database WITHOUT touching the deployed site files:
  - Copies the live public\web.config from RemoteDir into WorkDir, so runMigrations.vbs picks
    up the real production connection string without it being hard-coded here.
  - Runs `runMigrations.vbs status` (for the log) then `up` from WorkDir.
  - Deletes WorkDir when done, win or lose - nothing is left behind on the server.
#>

param(
  [Parameter(Mandatory = $true)][string]$RemoteDir,
  [Parameter(Mandatory = $true)][string]$WorkDir
)

$ErrorActionPreference = 'Stop'

$liveWebConfig = Join-Path $RemoteDir 'public\web.config'
if(!(Test-Path $liveWebConfig)){
  throw "No deployed web.config found at $liveWebConfig - is the site actually deployed at -RemoteDir?"
}

$workPublicDir = Join-Path $WorkDir 'public'
New-Item -ItemType Directory -Force -Path $workPublicDir | Out-Null
Copy-Item $liveWebConfig (Join-Path $workPublicDir 'web.config') -Force

try {
  Push-Location $WorkDir
  Write-Host '-- status before --'
  & cscript.exe //nologo scripts\runMigrations.vbs status
  if($LASTEXITCODE -ne 0){ throw 'runMigrations.vbs status failed - see output above' }

  Write-Host ''
  Write-Host '-- applying pending migrations --'
  & cscript.exe //nologo scripts\runMigrations.vbs up
  if($LASTEXITCODE -ne 0){ throw 'runMigrations.vbs up failed - see output above' }
} finally {
  Pop-Location
  Write-Host ''
  Write-Host "Cleaning up $WorkDir"
  Remove-Item -Recurse -Force $WorkDir -ErrorAction SilentlyContinue
}

Write-Host 'Remote migration apply complete.'
