#!/usr/bin/env bash
#------------------------------------------------------------------------------
# Run a command only if this is a replica (standby or edge replica) server.
#------------------------------------------------------------------------------
set -uo pipefail

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

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

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

check_required_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 ---
if ! check_required_vars; then
    echo "Calling set_vars to initialize missing variables..."
    set_vars
fi

# --- Check again after set_vars ---
if ! check_required_vars; 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" || "${SERVER_TYPE}" == "p4d_edgerep" ]]; then
   exec "$@"
fi
