
param(
    [Parameter(Mandatory = $true)]
    [string]$sshKeyPath,
    [Parameter(Mandatory = $true)]
    [int]$sshPort,
    [Parameter(Mandatory = $false)]
    [switch]$useCompression,
    [Parameter(Mandatory = $false)]
    [int]$verbosityLevel = 0,
    [Parameter(Mandatory = $true)]
    [string]$remoteServerUserName,
    [Parameter(Mandatory = $true)]
    [string]$remoteServerIpAddress,
    [Parameter(Mandatory = $true)]
    [string]$remoteServerSourceFolder,
    [Parameter(Mandatory = $true)]
    [string]$localDestinationFolderCygwin,
    [Parameter(Mandatory = $false)]
    [string]$customArguments = "",
    [Parameter(Mandatory = $false)]
    [string]$localDestinationFolder
)

Set-Location $PSScriptRoot
.($PSScriptRoot+"\..\AOFLibrary\AOFLibrary.ps1")
$ScriptName = "SyncDiskTemplate"
$LogFile = BeginScriptLogging -ScriptName $ScriptName

$sshKeyPath = Resolve-Path -Path $sshKeyPath

$rsyncExecutable = "C:\cygwin64\bin\rsync.exe"
$sshExecutable = "C:\cygwin64\bin\ssh.exe" # MUST BE FULL PATH

$argumentList = New-Object Collections.Generic.List[string]
$argumentList.Add("-a")
$argumentList.Add("-s")

if($verbosityLevel) {
    $argumentList.Add('-' + (New-Object System.String 'v', $verbosityLevel))
}
if($useCompression) {
    $argumentList.Add("-z")
}

if($customArguments)
{
    $argumentList.Add($customArguments)
}

$argumentList.Add("-e ""$sshExecutable -o StrictHostKeyChecking=no -i $sshKeyPath -p $sshPort""")
$argumentList.Add("--stats")
$argumentList.Add("--inplace")
$argumentList.Add("--delete")
$argumentList.Add("$remoteServerUserName@${remoteServerIpAddress}:$remoteServerSourceFolder")
$argumentList.Add($localDestinationFolderCygwin)

Write-Log -Message "Executing command: $rsyncExecutable $($argumentList -Join "" "")" -Level INFO -Log $LogFile 

$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo
$processStartInfo.FileName = $rsyncExecutable
$processStartInfo.Arguments = $argumentList
$processStartInfo.RedirectStandardOutput = $true
$processStartInfo.RedirectStandardError = $true
$processStartInfo.UseShellExecute = $false
$processStartInfo.CreateNoWindow = $true

$process = New-Object System.Diagnostics.Process
$process.StartInfo = $processStartInfo
$process.Start()

$output = $process.StandardOutput.ReadToEnd()
$errorOutput = $process.StandardError.ReadToEnd()

$process.WaitForExit()
$output

# propagate the exit code from rsync to agent.api
if($process.ExitCode -ne 0) {
    HandleScriptExecutionError -Message "Rsync error`r`nError: $errorOutput" -Log $LogFile
}
if ($localDestinationFolder)
{
    $manifestFolder = "$localDestinationFolder\PreinstalledGameLibraries\SteamLibrary\steamapps"
    Get-ChildItem -Recurse -Path "$manifestFolder" -Filter "appmanifest*.acf" | ForEach-Object {
        $manifest = Get-Content -Raw -Path $_.FullName
        $manifest = $manifest -replace """AutoUpdateBehavior""\s*""\d+""", """AutoUpdateBehavior""`t`t""1"""
        $utf8NoBom = New-Object System.Text.UTF8Encoding($false)
        [System.IO.File]::WriteAllText($_.FullName, $manifest, $utf8NoBom)
    }
}

Stop-Transcript
exit $process.ExitCode
# example: rsync -a -z -s -e 'ssh -i ~/.ssh/aofg_sync -p 2222' --stats username@192.168.1.30:/mnt/data/games_shared_folder/SteamLibrary /cygdrive/e/compression
