#!/bin/bash

# OCF Resource Agent:
#   loxthelion:managed-container
#
# v0.4
# Container lifecycle: systemd user Quadlet
# Application profile: PostgreSQL
#
# Version 0.4 adds explicit PostgreSQL demotion scaffolding.
# Healthy primaries report OCF_RUNNING_PROMOTED while healthy standbys
# report OCF_SUCCESS.

: "${OCF_ROOT:=/usr/lib/ocf}"
OCF_FUNCTIONS_DIR="${OCF_ROOT}/lib/heartbeat"
# Preserve explicit resource identity before ocf-shellfuncs supplies its
# standalone-invocation default; never publish a score for that dummy resource.
MC_PROMOTION_RESOURCE_INSTANCE="${OCF_RESOURCE_INSTANCE:-}"
. "${OCF_FUNCTIONS_DIR}/ocf-shellfuncs"

# Pacemaker uses "Promoted" terminology, while many OCF shell libraries
# still expose the historical OCF_RUNNING_MASTER constant for return code 8.
# Normalize both forms here so the agent remains portable.
: "${OCF_RUNNING_PROMOTED:=${OCF_RUNNING_MASTER:-8}}"


# Resolve modules relative to this entrypoint, independent of Pacemaker's cwd.
MC_MODULE_DIR="$(CDPATH= cd -- "$(command dirname -- "${BASH_SOURCE[0]}")" && pwd)/managed-container.d"
for MC_MODULE in common container postgres auth replication notify promote demote rejoin; do
    if ! . "${MC_MODULE_DIR}/${MC_MODULE}.sh"; then
        ocf_exit_reason "Unable to load resource-agent module ${MC_MODULE_DIR}/${MC_MODULE}.sh"
        exit "${OCF_ERR_CONFIGURED}"
    fi
done
unset MC_MODULE

case "$1" in
    meta-data)
        mc_promotion_metadata
        exit "${OCF_SUCCESS}"
        ;;

    validate-all)
        mc_promotion_validate
        exit $?
        ;;

    monitor|status)
        mc_promotion_monitor
        exit $?
        ;;

    start)
        mc_promotion_action start
        exit $?
        ;;

    stop)
        mc_promotion_action stop
        exit $?
        ;;

    promote)
        mc_promotion_action promote
        exit $?
        ;;

    demote)
        mc_promotion_action demote
        exit $?
        ;;

    notify)
        managed_notify
        exit $?
        ;;

    rejoin)
        mc_promotion_action rejoin
        exit $?
        ;;

    *)
        echo "Usage: $0 {start|stop|promote|demote|notify|rejoin|monitor|status|validate-all|meta-data}"
        exit "${OCF_ERR_UNIMPLEMENTED}"
        ;;
esac
