#!/usr/bin/env bash
set -euo pipefail

if [[ ${EUID} -ne 0 ]]; then
  printf '%s\n' "change-public-host must run as root" >&2
  exit 1
fi

old_host=${1:-}
new_host=${2:-}
if [[ -z "$old_host" || -z "$new_host" || "$old_host" == "$new_host" ]]; then
  printf '%s\n' "usage: change-public-host.sh <old-host> <new-host>" >&2
  exit 1
fi

roots=(/etc/harbor /etc/nginx /opt/harbor/deploy)
mapfile -t files < <(python3 - "$old_host" "${roots[@]}" <<'PY'
from pathlib import Path
import sys

needle = sys.argv[1]
seen = set()
for root in sys.argv[2:]:
    for path in Path(root).rglob("*"):
        try:
            if not path.is_file():
                continue
            resolved = path.resolve()
            if resolved in seen:
                continue
            text = path.read_text(errors="strict")
            if needle in text:
                seen.add(resolved)
                print(resolved)
        except (OSError, UnicodeError):
            pass
PY
)

if [[ ${#files[@]} -eq 0 ]]; then
  printf '%s\n' "no occurrences of $old_host found"
  exit 0
fi

stamp=$(date -u +%Y%m%dT%H%M%SZ)
backup="/var/backups/harbor/domain-change-$stamp.tar.gz"
install -d -m 0700 "$(dirname "$backup")"
tar -czf "$backup" "${files[@]}"
printf '%s\n' "backup: $backup"

python3 - "$old_host" "$new_host" "${files[@]}" <<'PY'
from pathlib import Path
import sys

old, new = sys.argv[1:3]
for name in sys.argv[3:]:
    path = Path(name)
    text = path.read_text()
    count = text.count(old)
    if count:
        path.write_text(text.replace(old, new))
        print(f"{path}: replaced {count}")
PY

nginx -t
systemctl reload nginx

slot=$(cat /etc/harbor/active-slot)
systemctl restart "harbor-gateway@$slot.service" "harbor-worker@$slot.service"

compose=(docker compose --env-file /etc/harbor/harbor.env -f /opt/harbor/deploy/compose/docker-compose.yml)
"${compose[@]}" up -d minio prometheus

remaining=$(python3 - "$old_host" "${roots[@]}" <<'PY'
from pathlib import Path
import sys

needle = sys.argv[1]
count = 0
for root in sys.argv[2:]:
    for path in Path(root).rglob("*"):
        try:
            if path.is_file() and needle in path.read_text(errors="strict"):
                print(path)
                count += 1
        except (OSError, UnicodeError):
            pass
print(count)
PY
)
remaining_count=${remaining##*$'\n'}
if [[ "$remaining_count" != 0 ]]; then
  printf '%s\n' "$remaining" >&2
  printf '%s\n' "old host still exists in $remaining_count file(s)" >&2
  exit 1
fi

curl -fsS http://127.0.0.1/health >/dev/null
printf '%s\n' "public host changed: $old_host -> $new_host"
