#!/usr/bin/env bash

set -Eeuo pipefail

run_id='q101-20260727T094445-repair'
backup_root='/var/backups/zhct-q101/files'
nginx_conf='/usr/local/nginx/conf/nginx.conf'
repair_backup="$backup_root/$run_id/usr/local/nginx/conf/nginx.conf"

print_state() {
    local unit
    for unit in nginx haproxy orchestrator sentinel5 sentinel7 keepalived; do
        printf 'UNIT=%s ENABLED=' "$unit"
        systemctl is-enabled "$unit" || true
        printf 'UNIT=%s ACTIVE=' "$unit"
        systemctl is-active "$unit" || true
    done
    ss -lntup || true
    ip -o -4 addr show || true
}

on_error() {
    local rc=$?
    trap - ERR
    echo "Q101_REPAIR_FAILED_RC=$rc"
    print_state
    echo 'Q101_REPAIR_FAILED_STOP_NO_RETRY'
    exit "$rc"
}
trap on_error ERR

echo 'Q101_REPAIR_BEGIN'
date -Is

[[ "$(hostname -s)" == 'sqjcnginx01' ]]
ip -o -4 addr show scope global | grep -F '10.2.203.102/'
[[ "$(grep -Fxc '    include conf.d/*.conf;' "$nginx_conf")" -eq 1 ]]
grep -Fq 'include conf.d/file-primary-routes.conf;' \
    /usr/local/nginx/conf/conf.d/front.conf

install -d -m 0750 -o root -g root "$(dirname "$repair_backup")"
cp -a "$nginx_conf" "$repair_backup"

temp=$(mktemp)
trap 'rm -f "$temp"' EXIT
sed 's|^    include conf\.d/\*\.conf;$|    include conf.d/front.conf;|' \
    "$nginx_conf" >"$temp"
[[ "$(grep -Fxc '    include conf.d/front.conf;' "$temp")" -eq 1 ]]
! grep -Fq 'include conf.d/*.conf;' "$temp"
install -m 0644 -o root -g root "$temp" "$nginx_conf"

/usr/local/nginx/sbin/nginx -t
echo 'Q101_NGINX_CONTEXT_REPAIR=PASS'

env RUN_ID="$run_id" BACKUP_ROOT="$backup_root" \
    /opt/zhct-deploy/common/scripts/activate-role.sh \
    --role nginx \
    --bundle-root /opt/zhct-deploy

echo 'Q101_RECOVERY_ACTIVATE_RC=0'
print_state

/usr/local/nginx/sbin/nginx -t
/usr/local/haproxy/sbin/haproxy -c -f /etc/haproxy/haproxy.cfg
/usr/local/sbin/keepalived \
    --config-test \
    --use-file=/etc/keepalived/keepalived.conf
python3 -m json.tool /etc/orchestrator.conf.json >/dev/null

for unit in nginx haproxy orchestrator; do
    systemctl is-enabled --quiet "$unit"
    systemctl is-active --quiet "$unit"
done

for unit in sentinel5 sentinel7 keepalived; do
    [[ "$(systemctl is-enabled "$unit" 2>/dev/null || true)" == 'disabled' ]]
    [[ "$(systemctl is-active "$unit" 2>/dev/null || true)" == 'inactive' ]]
done

if ip -o -4 addr show | grep -Eq '10\.2\.203\.(115|116|117)/'; then
    echo 'Q101_UNEXPECTED_VIP_PRESENT'
    exit 1
else
    echo 'Q101_VIP_ABSENT=PASS'
fi

curl -fsS --max-time 5 http://127.0.0.1:8081/__edge_health
echo
echo 'Q101_REPAIR_AND_ACTIVATE_PASS'
