# ============================================================================
# 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
        Recreate-live-from-offline-db.ps1 updates the offline database and then swaps it over to
        replace the live database.
        
    .Description
        Admin access is required.
        
    .Parameter sdp-instance
        The specified instance to process
        
    .Example
        Recreate-live-from-offline-db.ps1 Master
        
    .Example
        Recreate-live-from-offline-db.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 = "recreate-live-from-offline-db.ps1"
$global:ScriptTask = "Recreate Live DB Files"
$global:LogFileName = "checkpoint.log"

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

if (!(Test-IsAdmin)) {
    write-warning "Please run this script with admin privileges"
    break
}

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

try {
    Check-OfflineDBExists 
    Check-OfflineDBUsable
    Ensure-CheckpointNotRunning
    Invoke-P4Login
    Get-CurrentJournalCounter
    Get-OfflineJournalCounter
    Stop-LiveService
    Truncate-Journal
    Replay-JournalsToOfflineDB
    Move-OfflineDBToLive
    Start-LiveService
    Recreate-OfflineDBFiles
    Rotate-Logfiles
    Remove-OldCheckpointsAndJournals
    Log-DiskSpace
    Remove-OldLogs
    Log "End ${global:SDP_INSTANCE_P4SERVICE_NAME} ${global:ScriptTask}"
    Send-Email "${env:computername} ${global:SDP_INSTANCE_P4SERVICE_NAME} ${global:ScriptTask} log."
    Set-Counter
    Signal-CheckpointComplete
    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
