#!/usr/bin/env bash

set -Eeuo pipefail

run_id='q101-20260727T112000-bundle-refresh'
staging_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
bundle_root='/opt/zhct-deploy'
backup_root="/var/backups/zhct-q101/files/$run_id"
bundle_manifest="$bundle_root/manifests/bundle.sha256"

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
    ip -o -4 addr show || true
}

on_error() {
    local rc=$?
    trap - ERR
    echo "Q101_BUNDLE_REFRESH_FAILED_RC=$rc"
    print_state
    systemctl status nginx.service --no-pager -l || true
    echo 'Q101_BUNDLE_REFRESH_FAILED_STOP_NO_RETRY'
    exit "$rc"
}
trap on_error ERR

backup_file() {
    local source=$1
    local target="$backup_root/${source#/}"
    [[ -e "$source" ]]
    install -d -m 0750 -o root -g root "$(dirname "$target")"
    cp -a "$source" "$target"
}

echo 'Q101_BUNDLE_REFRESH_BEGIN'
date -Is

[[ "$(hostname -s)" == 'sqjcnginx01' ]]
ip -o -4 addr show scope global | grep -F '10.2.203.102/'

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

printf '%s  %s\n' \
    'be54d0b36f9ae5319f942f36c0f4e9681571c3210e8bd4e3382fe270ec101659' "$bundle_root/roles/nginx/templates/nginx/nginx.conf" \
    '52c3261326cd09781b7cef59fe89e1ffa67a6bb40a316ddfc09bd43c5ce246bf' "$bundle_root/roles/nginx/hooks.sh" \
    '128453c793f540126181db45ac3b12e7d0c755156b6b4b1c84cc188f8eaea942' "$bundle_root/roles/nginx/templates/systemd/nginx.service" |
    sha256sum -c -
[[ ! -e "$bundle_root/validate-assets.sh" ]]

grep -Fxq '52c3261326cd09781b7cef59fe89e1ffa67a6bb40a316ddfc09bd43c5ce246bf  roles/nginx/hooks.sh' "$bundle_manifest"
grep -Fxq 'be54d0b36f9ae5319f942f36c0f4e9681571c3210e8bd4e3382fe270ec101659  roles/nginx/templates/nginx/nginx.conf' "$bundle_manifest"
grep -Fxq '128453c793f540126181db45ac3b12e7d0c755156b6b4b1c84cc188f8eaea942  roles/nginx/templates/systemd/nginx.service' "$bundle_manifest"
grep -Fxq '921bb6f6d6a057ba01713ca3fcea94c6b0a0cbf662b34bae9058fa01bf8a907e  validate-assets.sh' "$bundle_manifest"

printf '%s  %s\n' \
    'b4905680419a0ad3d9a8ea9298dec5f4f2f5e5ef2f3ffe42d2119a1aafe9df62' "$staging_dir/nginx.conf" \
    '92c3b974b74c9d128c52a989624c97a1bb6ba77057dd02cf6de6421d3087f105' "$staging_dir/hooks.sh" \
    'd214722459a5029b601522957dbb6b3b710e87bd2c090768dec965d680bf55e0' "$staging_dir/nginx.service" \
    '811409c6721b1c8f5c5b8fc1c8db67a8386cb712a93e617178015b97e3eb5177' "$staging_dir/validate-assets.sh" |
    sha256sum -c -

backup_file "$bundle_root/roles/nginx/templates/nginx/nginx.conf"
backup_file "$bundle_root/roles/nginx/hooks.sh"
backup_file "$bundle_root/roles/nginx/templates/systemd/nginx.service"
backup_file "$bundle_manifest"
backup_file /etc/systemd/system/nginx.service

install -m 0644 -o root -g root \
    "$staging_dir/nginx.conf" \
    "$bundle_root/roles/nginx/templates/nginx/nginx.conf"
install -m 0755 -o root -g root \
    "$staging_dir/hooks.sh" \
    "$bundle_root/roles/nginx/hooks.sh"
install -m 0644 -o root -g root \
    "$staging_dir/nginx.service" \
    "$bundle_root/roles/nginx/templates/systemd/nginx.service"
install -m 0755 -o root -g root \
    "$staging_dir/validate-assets.sh" \
    "$bundle_root/validate-assets.sh"

manifest_temp=$(mktemp)
trap 'rm -f "$manifest_temp"' EXIT
python3 - "$bundle_manifest" "$manifest_temp" <<'PY'
import pathlib
import sys

source = pathlib.Path(sys.argv[1])
target = pathlib.Path(sys.argv[2])
text = source.read_text(encoding="utf-8")
replacements = {
    "52c3261326cd09781b7cef59fe89e1ffa67a6bb40a316ddfc09bd43c5ce246bf  roles/nginx/hooks.sh":
        "92c3b974b74c9d128c52a989624c97a1bb6ba77057dd02cf6de6421d3087f105  roles/nginx/hooks.sh",
    "be54d0b36f9ae5319f942f36c0f4e9681571c3210e8bd4e3382fe270ec101659  roles/nginx/templates/nginx/nginx.conf":
        "b4905680419a0ad3d9a8ea9298dec5f4f2f5e5ef2f3ffe42d2119a1aafe9df62  roles/nginx/templates/nginx/nginx.conf",
    "128453c793f540126181db45ac3b12e7d0c755156b6b4b1c84cc188f8eaea942  roles/nginx/templates/systemd/nginx.service":
        "d214722459a5029b601522957dbb6b3b710e87bd2c090768dec965d680bf55e0  roles/nginx/templates/systemd/nginx.service",
    "921bb6f6d6a057ba01713ca3fcea94c6b0a0cbf662b34bae9058fa01bf8a907e  validate-assets.sh":
        "811409c6721b1c8f5c5b8fc1c8db67a8386cb712a93e617178015b97e3eb5177  validate-assets.sh",
}
for old, new in replacements.items():
    if text.count(old) != 1:
        raise SystemExit(f"manifest precondition failed: {old}")
    text = text.replace(old, new)
target.write_text(text, encoding="utf-8")
PY
install -m 0644 -o root -g root "$manifest_temp" "$bundle_manifest"

(cd "$bundle_root" && sha256sum -c manifests/bundle.sha256)
"$bundle_root/validate-assets.sh"

cmp -s "$bundle_root/roles/nginx/templates/nginx/nginx.conf" \
    /usr/local/nginx/conf/nginx.conf
install -m 0644 -o root -g root \
    "$bundle_root/roles/nginx/templates/systemd/nginx.service" \
    /etc/systemd/system/nginx.service

systemctl daemon-reload
/usr/local/nginx/sbin/nginx -t
systemctl restart nginx.service
systemctl is-enabled --quiet nginx.service
systemctl is-active --quiet nginx.service

nginx_pid=$(systemctl show nginx.service -p MainPID --value)
nginx_soft_limit=$(awk '/Max open files/ {print $4}' "/proc/$nginx_pid/limits")
[[ "$nginx_soft_limit" -eq 65535 ]]
printf 'NGINX_MAIN_PID=%s\n' "$nginx_pid"
printf 'NGINX_OPEN_FILES_SOFT=%s\n' "$nginx_soft_limit"

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

for unit in 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

print_state
echo 'Q101_BUNDLE_REFRESH_PASS'
