param([Parameter(Mandatory = $true)][int]$ProcessId)

$ErrorActionPreference = 'Stop'
$repo = Join-Path $env:USERPROFILE 'TibiaPilotNG'
$resultFile = Join-Path $repo '.update-result.json'
$deployKey = Join-Path $env:USERPROFILE '.ssh\tibiapilot_update'
$taskName = 'TibiaPilotNG'
$result = @{
    ok = $false
    message = 'Update fehlgeschlagen.'
}

function Invoke-Git {
    param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Arguments)
    $output = & git -C $repo @Arguments 2>&1
    if ($LASTEXITCODE -ne 0) {
        throw ($output -join [Environment]::NewLine)
    }
    return $output
}

try {
    Wait-Process -Id $ProcessId -Timeout 20 -ErrorAction SilentlyContinue
    if (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue) {
        Stop-Process -Id $ProcessId -Force
    }
    if (!(Test-Path $deployKey)) {
        throw 'Der private Update-Schlüssel fehlt.'
    }

    $trackedChanges = Invoke-Git status --porcelain --untracked-files=no
    if ($trackedChanges) {
        throw 'Lokale Programmdateien wurden verändert. Update abgebrochen.'
    }

    $env:GIT_TERMINAL_PROMPT = '0'
    $env:GIT_SSH_COMMAND = "ssh -i `"$deployKey`" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o BatchMode=yes"
    $oldHead = (Invoke-Git rev-parse HEAD | Select-Object -First 1)
    $oldLock = (Invoke-Git rev-parse 'HEAD:poetry.lock' | Select-Object -First 1)
    Invoke-Git fetch --quiet origin master | Out-Null
    $remoteHead = (Invoke-Git rev-parse origin/master | Select-Object -First 1)

    if ($oldHead -eq $remoteHead) {
        $result.ok = $true
        $result.message = 'PilotNG ist bereits aktuell.'
    } else {
        Invoke-Git merge --ff-only origin/master | Out-Null
        $newLock = (Invoke-Git rev-parse 'HEAD:poetry.lock' | Select-Object -First 1)
        if ($oldLock -ne $newLock) {
            $python = Join-Path $repo '.venv\Scripts\python.exe'
            & $python -m pip install --disable-pip-version-check --no-input $repo
            if ($LASTEXITCODE -ne 0) {
                throw 'Python-Abhängigkeiten konnten nicht aktualisiert werden.'
            }
        }
        $result.ok = $true
        $result.message = 'Update wurde installiert.'
    }
} catch {
    $result.message = $_.Exception.Message
} finally {
    $result | ConvertTo-Json | Set-Content $resultFile -Encoding utf8
    Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
    Start-ScheduledTask -TaskName $taskName
}
