#!/usr/bin/env bash
#==============================================================================
# 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
#------------------------------------------------------------------------------

instance=${1}
if [ ! -d /p4/${instance} ]; then
  exit 0 
fi
shift

# Load SDP environment functions
source /p4/common/bin/p4_vars "$instance"
source /p4/common/bin/backup_functions.sh

# List of variables that must be set before continuing
required_vars=(SERVER_TYPE P4REPLICA EDGESERVER)

check_vars() {
    local missing=0
    for v in "${required_vars[@]}"; do
        if [[ -z "${!v}" ]]; then
            echo "Missing required variable: $v"
            missing=1
        fi
    done
    return $missing
}

# --- First check ---
check_vars
if [[ $? -ne 0 ]]; then
    echo "Calling set_vars to initialize missing variables..."
    set_vars
fi

# --- Check again after set_vars ---
check_vars
if [[ $? -ne 0 ]]; then
    echo "ERROR: Required variables are still missing after calling set_vars."
    exit 1
fi

# --- Script logic now safe to execute ---

if [[ "${SERVER_TYPE}" == "p4proxy" ]]; then
   exit 0
fi

if [[ "${SERVER_TYPE}" == "p4d_standby" ]]; then
   exec $@
fi
