#!/usr/bin/env bash

set -Eeuo pipefail

ACTION=${1:-}
DRY_RUN=0
[[ $# -le 2 ]] || { echo 'usage: vip-control.sh <enable|disable|status> [--dry-run]' >&2; exit 2; }
[[ -z "${2:-}" || "${2:-}" == "--dry-run" ]] || { echo "unknown argument: ${2:-}" >&2; exit 2; }
[[ "${2:-}" == "--dry-run" ]] && DRY_RUN=1

case "$ACTION" in
    enable|disable|status) ;;
    *) echo 'usage: vip-control.sh <enable|disable|status> [--dry-run]' >&2; exit 2 ;;
esac

if [[ "$ACTION" == status ]]; then
    systemctl status keepalived.service --no-pager
    ip -4 address show | grep -E '10\.2\.203\.(115|116|117)/' || true
    exit 0
fi

if ((DRY_RUN)); then
    printf 'DRY-RUN: would %s Keepalived and the three independent VIPs\n' "$ACTION"
    exit 0
fi

[[ $(id -u) -eq 0 ]] || { echo 'root is required' >&2; exit 1; }

if [[ "$ACTION" == disable ]]; then
    systemctl disable --now keepalived.service
    sleep 2
    ! ip -4 address show | grep -Eq '10\.2\.203\.(115|116|117)/'
    exit 0
fi

for config in /etc/keepalived/keepalived.conf /etc/haproxy/haproxy.cfg; do
    [[ -r "$config" ]] || { echo "missing config: $config" >&2; exit 1; }
    ! grep -Eq '__[A-Z0-9_]+__' "$config" || { echo "unresolved placeholder: $config" >&2; exit 1; }
done
systemctl is-active --quiet nginx.service
systemctl is-active --quiet haproxy.service
/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
/usr/local/sbin/check-front-vip.sh
/usr/local/sbin/check-mqtt-vip.sh
/usr/local/sbin/check-db-proxy-vip.sh
systemctl enable --now keepalived.service
systemctl is-active --quiet keepalived.service
