#!/usr/bin/env bash

# HA monitoring script
# Checks XiVO PBX HA status and stops local nginx if not active

if [ -f /etc/docker/compose/.env ]; then
    source /etc/docker/compose/.env
elif [ -f /etc/docker/compose/custom.env ]; then
    source /etc/docker/compose/custom.env
else
    logger -t xivocc-ha -p user.err "[RESILIENCE] Cannot find environment file"
    exit 1
fi

is_nginx_running() {
    docker ps --filter "name=nginx" --filter "status=running" --format "{{.Names}}" 2>/dev/null | grep -q nginx
}

API_URL="https://${XIVO_HOST}/configmgt/api/2.0/sysconfd/get_ha_config"
RESPONSE_FILE="/tmp/xivo_ha_config_resp.json"
TEMP_RESPONSE_FILE="/tmp/xivo_ha_config_resp.json.new"

logger -t xivocc-ha -p user.info "[RESILIENCE] Querying HA status at $API_URL"
HTTP_CODE=$(curl -k -s -o "$TEMP_RESPONSE_FILE" -w "%{http_code}" \
    -H 'accept: application/json' \
    -H "X-Auth-Token: ${PLAY_AUTH_TOKEN}" \
    "$API_URL" 2>/dev/null || echo "000")

if [ "$HTTP_CODE" != "200" ]; then
    logger -t xivocc-ha -p user.warning "[RESILIENCE] No valid response from HA API (HTTP $HTTP_CODE)"
    rm -f "$TEMP_RESPONSE_FILE"

    if [ -f "$RESPONSE_FILE" ]; then
        PREV_NODE_TYPE=$(jq -r 'if .node_type == null then "null" else (.node_type | tostring) end' "$RESPONSE_FILE" 2>/dev/null || echo "null")

        if [ "$PREV_NODE_TYPE" != "disabled" ] && [ "$PREV_NODE_TYPE" != "null" ]; then
            logger -t xivocc-ha -p user.warning "[RESILIENCE] Previous HA config node_type=$PREV_NODE_TYPE, HA was configured"
            if is_nginx_running; then
                logger -t xivocc-ha -p user.warning "[RESILIENCE] Stopping nginx due to XiVO unavailability"
                /usr/bin/xivocc-dcomp stop nginx
            else
                logger -t xivocc-ha -p user.info "[RESILIENCE] Nginx already stopped"
            fi
            exit 0
        else
            logger -t xivocc-ha -p user.info "[RESILIENCE] Previous HA config node_type=$PREV_NODE_TYPE, no action needed"
            exit 0
        fi
    else
        logger -t xivocc-ha -p user.info "[RESILIENCE] No previous HA config found, no action needed"
        exit 0
    fi
fi

mv "$TEMP_RESPONSE_FILE" "$RESPONSE_FILE"

NODE_TYPE=$(jq -r 'if .node_type == null then "null" else (.node_type | tostring) end' "$RESPONSE_FILE" 2>/dev/null || echo "null")
ACTIVE=$(jq -r 'if .active == null then "null" else (.active | tostring) end' "$RESPONSE_FILE" 2>/dev/null || echo "null")

if [ "$NODE_TYPE" = "disabled" ]; then
    logger -t xivocc-ha -p user.info "[RESILIENCE] HA node_type is disabled, skipping monitoring"
    exit 0
fi

if [ "$ACTIVE" = "false" ]; then
    logger -t xivocc-ha -p user.warning "[RESILIENCE] HA config shows active=false"
    if is_nginx_running; then
        logger -t xivocc-ha -p user.warning "[RESILIENCE] Stopping nginx (standby mode)"
        /usr/bin/xivocc-dcomp stop nginx
    else
        logger -t xivocc-ha -p user.info "[RESILIENCE] Nginx already stopped"
    fi
    exit 0
elif [ "$ACTIVE" = "true" ]; then
    logger -t xivocc-ha -p user.info "[RESILIENCE] HA config shows active=true"
    if ! is_nginx_running; then
        logger -t xivocc-ha -p user.warning "[RESILIENCE] Starting nginx (active mode)"
        /usr/bin/xivocc-dcomp start nginx
    else
        logger -t xivocc-ha -p user.info "[RESILIENCE] Nginx already running"
    fi
    exit 0
fi

logger -t xivocc-ha -p user.warning "[RESILIENCE] HA status unknown (active=$ACTIVE), no action taken"
exit 0

