param([switch]$AllowUninitialized)

$ErrorActionPreference = 'Stop'

$repo = Join-Path $env:USERPROFILE 'TibiaPilotNG'
$live = Join-Path $env:LOCALAPPDATA 'Tibia\packages\Tibia\conf\clientoptions.json'
$liveCharacters = Join-Path $env:LOCALAPPDATA 'Tibia\packages\Tibia\characterdata'
$root = Join-Path $env:LOCALAPPDATA 'TibiaPilotNG'
$profiles = Join-Path $root 'profiles'
$marker = Join-Path $root 'active-profile.txt'
$launcher = Join-Path $repo 'tools\Start-PilotNG-OneClick.ps1'
$normalLauncher = Join-Path $repo 'tools\Start-Tibia-Normal.ps1'
$uiLauncher = Join-Path $repo 'tools\Start-TibiaPilotNG.ps1'

$clientInitialized = (Test-Path $live) -and (Test-Path $liveCharacters)
if (!$clientInitialized -and !$AllowUninitialized) {
    throw 'Tibia muss einmal normal gestartet werden, damit sein lokales Profil angelegt wird.'
}
if ($clientInitialized) {
    foreach ($profile in @('normal', 'bot')) {
        $directory = Join-Path $profiles $profile
        $file = Join-Path $directory 'clientoptions.json'
        $characters = Join-Path $directory 'characterdata'
        New-Item $directory -ItemType Directory -Force | Out-Null
        if (!(Test-Path $file)) { Copy-Item $live $file }
        if (!(Test-Path $characters)) {
            & robocopy.exe $liveCharacters $characters /MIR /COPY:DAT /DCOPY:DAT /R:2 /W:1 /NFL /NDL /NJH /NJS /NP | Out-Null
            if ($LASTEXITCODE -ge 8) { throw "Could not initialize $profile characterdata." }
        }
    }
}
if (!(Test-Path $marker)) { Set-Content $marker 'normal' -Encoding ascii }

$admins = ([Security.Principal.SecurityIdentifier]'S-1-5-32-544').Translate([Security.Principal.NTAccount]).Value
$system = ([Security.Principal.SecurityIdentifier]'S-1-5-18').Translate([Security.Principal.NTAccount]).Value
$user = "$env:COMPUTERNAME\$env:USERNAME"
icacls.exe $root /inheritance:r /grant:r "${admins}:(OI)(CI)(F)" "${system}:(OI)(CI)(F)" "${user}:(OI)(CI)(F)" | Out-Null

$taskName = 'TibiaPilotNG-OneClick'
$action = New-ScheduledTaskAction `
    -Execute "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
    -Argument "-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$launcher`"" `
    -WorkingDirectory $repo
$principal = New-ScheduledTaskPrincipal `
    -UserId $user `
    -LogonType Interactive `
    -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet `
    -MultipleInstances IgnoreNew `
    -ExecutionTimeLimit (New-TimeSpan -Days 3650)

$uiTaskName = 'TibiaPilotNG'
$uiAction = New-ScheduledTaskAction `
    -Execute "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
    -Argument "-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$uiLauncher`"" `
    -WorkingDirectory $repo
Register-ScheduledTask `
    -TaskName $uiTaskName `
    -Action $uiAction `
    -Principal $principal `
    -Settings $settings `
    -Force | Out-Null

Register-ScheduledTask `
    -TaskName $taskName `
    -Action $action `
    -Principal $principal `
    -Settings $settings `
    -Force | Out-Null

$normalTaskName = 'Tibia-Normal'
$normalAction = New-ScheduledTaskAction `
    -Execute "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
    -Argument "-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$normalLauncher`"" `
    -WorkingDirectory $repo
Register-ScheduledTask `
    -TaskName $normalTaskName `
    -Action $normalAction `
    -Principal $principal `
    -Settings $settings `
    -Force | Out-Null

$shell = New-Object -ComObject WScript.Shell
foreach ($directory in @(
    [Environment]::GetFolderPath('Desktop'),
    (Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs')
)) {
    foreach ($entry in @(
        @{ Name = 'TibiaPilotNG Bot'; Task = $taskName },
        @{ Name = 'Tibia Normal'; Task = $normalTaskName },
        @{ Name = 'PilotNG Einstellungen'; Task = $uiTaskName }
    )) {
        $shortcut = $shell.CreateShortcut((Join-Path $directory "$($entry.Name).lnk"))
        $shortcut.TargetPath = "$env:SystemRoot\System32\schtasks.exe"
        $shortcut.Arguments = "/Run /TN `"$($entry.Task)`""
        $shortcut.WorkingDirectory = $repo
        $shortcut.IconLocation = "$(Join-Path $env:LOCALAPPDATA 'Tibia\Tibia.exe'),0"
        $shortcut.Save()
    }
}

if ($clientInitialized) {
    Write-Output 'TibiaPilotNG Bot und Tibia Normal installiert.'
} else {
    Write-Output 'Start-Tasks installiert. Nach dem ersten normalen Tibia-Start tools\\Install-PilotNG-OneClick.ps1 erneut ausfuehren.'
}
