$ErrorActionPreference = "Stop"

$Root = "C:\UniDesk\personal-wechat"
$WcfRoot = Join-Path $Root "wcf\v39.5.2"
$PythonSite = Join-Path $WcfRoot "python-site"
$StateRoot = Join-Path $Root "wcf-state"
$DataRoot = Join-Path $Root "data\profile"
$AppData = Join-Path $DataRoot "AppData\Roaming"
$LocalAppData = Join-Path $DataRoot "AppData\Local"
$Documents = Join-Path $DataRoot "Documents"
$TempRoot = Join-Path $LocalAppData "Temp"
$Python = "C:\ProgramData\miniconda3\python.exe"
$Script = Join-Path $WcfRoot "wcf_host.py"
$PidFile = Join-Path $StateRoot "wcf-host.pid"
$Stdout = Join-Path $StateRoot "wcf-host.stdout.log"
$Stderr = Join-Path $StateRoot "wcf-host.stderr.log"
$Runner = Join-Path $StateRoot "wcf-host-runner.cmd"

New-Item -ItemType Directory -Force $StateRoot,$DataRoot,$AppData,$LocalAppData,$Documents,$TempRoot,$PythonSite | Out-Null

function Get-WcfProcessByPidFile {
  if (!(Test-Path -LiteralPath $PidFile)) { return $null }
  $oldPid = (Get-Content $PidFile -ErrorAction SilentlyContinue | Select-Object -First 1)
  if (!$oldPid) { return $null }
  return Get-Process -Id ([int]$oldPid) -ErrorAction SilentlyContinue
}

$existing = Get-WcfProcessByPidFile
if ($existing) {
  [pscustomobject]@{
    ok = $true
    alreadyRunning = $true
    pid = $existing.Id
    stdout = $Stdout
    stderr = $Stderr
    status = (Join-Path $StateRoot "status.json")
    dataRoot = $DataRoot
  } | ConvertTo-Json -Depth 6
  exit 0
}

# Keep this sandbox isolated from the daily Weixin/WeChat install. Only stop
# processes that were launched from the UniDesk personal-wechat tree/profile.
Get-CimInstance Win32_Process |
  Where-Object {
    ($_.ExecutablePath -like "$Root\*") -or
    ($_.CommandLine -like "*$WcfRoot\wcf_host.py*") -or
    ($_.Name -eq "WeChatAppEx.exe" -and $_.CommandLine -like "*$DataRoot*")
  } |
  ForEach-Object {
    try { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } catch {}
  }
Start-Sleep -Seconds 2

Remove-Item -Force (Join-Path $StateRoot "status.json") -ErrorAction SilentlyContinue
Remove-Item -Force (Join-Path $WcfRoot "injector.log") -ErrorAction SilentlyContinue
Remove-Item -Force $PidFile -ErrorAction SilentlyContinue

@"
@echo off
set WCF_COMMAND_PORT=10086
set WCF_STATE_ROOT=$StateRoot
set PYTHONPATH=$PythonSite
set USERPROFILE=$DataRoot
set APPDATA=$AppData
set LOCALAPPDATA=$LocalAppData
set HOMEDRIVE=C:
set HOMEPATH=\UniDesk\personal-wechat\data\profile
set TEMP=$TempRoot
set TMP=$TempRoot
mkdir "$TempRoot" 2>nul
cd /d "$WcfRoot"
"$Python" "$Script" > "$Stdout" 2> "$Stderr"
"@ | Set-Content -Encoding ASCII $Runner

$cmd = '/c start "" /min "' + $Runner + '"'
$launcher = Start-Process -FilePath "cmd.exe" -ArgumentList $cmd -WindowStyle Hidden -PassThru
Start-Sleep -Seconds 3
$pidValue = $null
if (Test-Path -LiteralPath $PidFile) {
  $pidValue = (Get-Content $PidFile -ErrorAction SilentlyContinue | Select-Object -First 1)
}

[pscustomobject]@{
  ok = $true
  started = $true
  launcherPid = $launcher.Id
  pid = $pidValue
  runner = $Runner
  stdout = $Stdout
  stderr = $Stderr
  status = (Join-Path $StateRoot "status.json")
  dataRoot = $DataRoot
  pythonSite = $PythonSite
  appData = $AppData
  localAppData = $LocalAppData
} | ConvertTo-Json -Depth 6
