# ============================================================================
# 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
        Recovers an edge server from specified Master checkpoint (which may be filtered)
        Particularly intended for use with filtered edge servers, but handles an 
        unfiltered edge server too.
        
    .Description
        Recover the edge server from the latest commit server checkpoint, while keeping
        any local edge server specific state such as db.have/db.working etc.
        
        The normal expectation is that you will use a checkpoint created by the
        script create-filtered-edge-checkpoint.ps1
        
        If you want the edge server to be filtered, then you MUST use that script.
        If you just use the latest Master/Commit server checkpoint as input, then
        the edge will be assumed to be unfiltered - this script will still work.
        
        NOTE:
        This script will stop and restart the edge server while it is running - so
        it will be unavailable for periods while this script is running.
        
        This script also resets the offline_db directory for the edge server.
        
        
    .Parameter SDPInstance
        The specified instance to process
        
    .Parameter CkpFile
        The specified (master/commit server) checkpoint file to recover from
        (assumed to be gzipped).
        
    .Example
        recover-edge.ps1 Edge1 p4_1.ckp.filtered-edge.1234.gz
        
        Will recover for SDP instance Edge1.
#>
# end::includeManual[]

[CmdletBinding()]
param ([string]$SDPInstance = $(throw "SDPInstance parameter is required."),
       [string]$CkpFile = $(throw "CKPFile 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 = "recover-edge.ps1"
$global:ScriptTask = "Recover edge server from master/commit checkpoint"
$global:LogFileName = "recover-edge.log"

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

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

try {
    remove-files "${global:OFFLINE_DB_DIR}\db." 0

    log "Recover checkpoint from master into offline_db skipping tables not used on the edge."
    $cmd = "$global:P4DEXE -r $global:OFFLINE_DB_DIR -K ""$global:EXCLUDED_EDGE_TABLES"" -jr -z $CkpFile"
    run-cmd $cmd "ERROR - attempting to recover offline db files"

    log "Stopping the edge server."
    Stop-LiveService
    
    log "Creating a dump of the edge specific data from P4ROOT"
    $edgedump = -join($global:CHECKPOINTS_DIR, "\edgedump")
    $md5file = -join($global:CHECKPOINTS_DIR, "\edgedump.md5")
    Rotate-File $md5file 
    Rotate-File $edgedump
    $cmd = "$global:P4DEXE -r $global:P4ROOT -k ""$global:EDGE_CHECKPOINT_TABLES"" -jd $edgedump"
    run-cmd $cmd "ERROR - attempting to create edgedump"

    log "Recover the edge dump into offline_db"
    $cmd = "$global:P4DEXE -r $global:OFFLINE_DB_DIR -k ""$global:EDGE_CHECKPOINT_TABLES"" -jr $edgedump"
    run-cmd $cmd "ERROR - attempting to recover from edgedump"

    log "Reset the replication state and clear the P4ROOT folder db files."
    remove-files "${global:P4ROOT}\db." 0
    remove-files "${global:P4ROOT}\state" 0
    remove-files "${global:P4ROOT}\rdb.lbr" 0
    remove-files "$global:P4JOURNAL" 0

    log "Move the rebuilt database to P4ROOT"
    move-files "${global:offline_db_dir}\db.*" $global:P4ROOT

    log "Start the edge server back up."
    Start-LiveService
    
    log "Recreate the offline_db"
    $cmd = "$global:P4DEXE -r $global:OFFLINE_DB_DIR -K ""$global:EXCLUDED_EDGE_TABLES"" -jr -z $CkpFile"
    run-cmd $cmd "ERROR - attempting to recreate offline_db"
    $cmd = "$global:P4DEXE -r $global:OFFLINE_DB_DIR -k ""$global:EDGE_CHECKPOINT_TABLES"" -jr $edgedump"
    run-cmd $cmd "ERROR - attempting to recreate offline_db from edgedump"
    $offline_db_usable = -join($global:OFFLINE_DB_DIR, "\offline_db_usable.txt")
    "Offline db file restored successfully." | set-content -path $offline_db_usable

    log "Create a new edge checkpoint from offline_db"
    $rebuilt_edge_dump = -join($global:CHECKPOINTS_DIR, "\rebuilt_edge_dump")
    $md5file = -join($global:CHECKPOINTS_DIR, "\rebuilt_edge_dump.md5")
    Rotate-File "$rebuilt_edge_dump.gz"
    Rotate-File $md5file 
    $cmd = "$global:P4DEXE -r $global:OFFLINE_DB_DIR -jd -z $rebuilt_edge_dump"
    run-cmd $cmd "ERROR - attempting to create new edge checkpoint"

    Log "End ${global:SDP_INSTANCE_P4SERVICE_NAME} ${global:ScriptTask}"
    Write-Output "`r`n${global:ScriptTask} completed successfully - see ${global:logfile}"
}
Catch
{
    write-error $error[0].ScriptStackTrace
    LogException $_.Exception
    Write-Output "`r`nFAILED - ${global:ScriptTask} - see ${global:logfile}"
}

Set-Location -Path $OrigPath
