# ============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Server Deployment Package (SDP), and also available online:
# https://swarm.workshop.perforce.com/projects/perforce-software-sdp/view/main/LICENSE
# ----------------------------------------------------------------------------

# tag::includeManual[]
<#
    .Synopsis
        upgrade.ps1 performs upgrades the specified Perforce SDP instance to a new version of p4d
        
    .Description
        Rotates the journal, stops the live service, updates the executable,
        updates the offline and root databases, and restarts the service.

        REQUIRED: prior to running, download new p4d.exe to c:\p4\common\bin

        This script is aware of p4d versions up to 20.1 (so recognised 19.1+ new db.storage)
        
    .Parameter sdp-instance
        The specified SDP instance to upgrade
        
    .Example
        upgrade.ps1 Master
        
    .Example
        upgrade.ps1 1
#>
# end::includeManual[]

[CmdletBinding()]
param ([string]$SDPInstance = $(throw "SDPInstance parameter is required."))

Set-StrictMode -Version 2.0

# Source the SDP Functions shared between scripts
$SDPFunctionsPath = Split-Path -parent $MyInvocation.MyCommand.Path | Join-Path -childpath "SDP-Functions.ps1" 
. $SDPFunctionsPath

$global:ScriptName = "Upgrade.ps1"
$global:ScriptTask = "Upgrade"
$global:LogFileName = "upgrade.log"

Parse-SDPConfigFile $MyInvocation.MyCommand.Path
Create-LogFile

$OrigPath = convert-path .
Set-Location -Path $global:LOGS_DIR

Function Run-Upgrade () {
    Log "Running upgrade"
    $p4 = -join($global:SCRIPTS_DIR, "\p4.exe")
    $p4d = -join($global:SCRIPTS_DIR, "\p4d.exe")
    Ensure-PathExists $p4
    Ensure-PathExists $p4d
    
    set-vars
    $curr_p4dver = & $global:P4dexe -V | select-string "^Rev" | %{$_.line.split("/")[2]}
    Log "Current server version: $curr_p4dver"
    Invoke-P4Login
    if (! $global:IS_REPLICASERVER -or ! $global:IS_EDGESERVER) {
        Get-CurrentJournalCounter
    }

    Stop-LiveService

    # Only rotate the journal on the master. 
    if (! $global:IS_REPLICASERVER -and ! $global:IS_EDGESERVER) {
        Get-OfflineJournalCounter
        Truncate-Journal
        Rotate-Logfiles
        Replay-JournalsToOfflineDB
    }

    $p4s = -join($global:SDP_INSTANCE_BIN_DIR, "\p4s.exe")
    copy-files $p4 $global:SDP_INSTANCE_BIN_DIR
    copy-files $p4d $global:SDP_INSTANCE_BIN_DIR
    copy-files $p4d $p4s
    
    # For versions >= 18.2 we should journal the upgrade and not upgrade offline
    # In such cases we let offline_db be upgraded by applying rotate journals in the
    # normal way.
    $p4dver = & $global:P4dexe -V | select-string "^Rev" | %{$_.line.split("/")[2]}
    Log "New server version: $p4dver"
    $upgrade_jnl = "$global:P4JOURNAL"
    if ($p4dver -lt "18.2") {
        $upgrade_jnl = "off"
    }

    $cmd = "$global:P4dexe -r $global:p4root -J $upgrade_jnl -xu"
    run-cmd $cmd "ERROR - attempting to upgrade db"
    
    # Upgrade the offline database on the master and on edge servers if required
    # Note that for 18.2 or later, upgrade of offline happens through journal 
    # rotation.
    if (! $global:IS_REPLICASERVER -or $global:IS_EDGESERVER) {
        if ($upgrade_jnl -eq "off") {
            Log "Upgrading offline_db as this is pre 18.2 server"
            $cmd = "$global:P4dexe -r $global:offline_db_dir -J $upgrade_jnl -xu"
            run-cmd $cmd "ERROR - attempting to upgrade db"
        } else {
            if (! $global:IS_REPLICASERVER -and ! $global:IS_EDGESERVER) {
                Log "Upgrading offline_db through journal rotation on master/commit server"
                $global:JOURNAL_NUM = $global:JOURNAL_NUM + 1
                $global:CHECKPOINT_NUM = $global:JOURNAL_NUM + 1
                Get-OfflineJournalCounter
                Truncate-Journal
                Replay-JournalsToOfflineDB
            }
        }
    }
    
    Start-LiveService

}

try {
    Check-AdminPrivileges
    Log "If there are errors in this log, you may wish to contact support-helix-core@perforce.com for help."
    Invoke-P4Login
    Run-Upgrade
    Remove-OldLogs
    Log "End ${global:SDP_INSTANCE_P4SERVICE_NAME} ${global:ScriptTask}"
    Send-Email "${env:computername} ${global:SDP_INSTANCE_P4SERVICE_NAME} ${global:ScriptTask} log."
    Write-Output "`r`n${global:ScriptTask} completed successfully - see ${global:logfile}"
}
Catch
{
    write-error $error[0].ScriptStackTrace
    LogException $_.Exception
    Send-Email "FAILED: ${env:computername} ${global:SDP_INSTANCE_P4SERVICE_NAME} ${global:ScriptTask} log."
    Write-Output "`r`nFAILED - ${global:ScriptTask} - see ${global:logfile}"
}

Set-Location -Path $OrigPath
