#!/usr/bin/env bash
set -euo pipefail
KEY="/etc/alfred/ha-standby-id_ed25519"
STANDBY=$(grep -E '^standby_ip=' /etc/alfred/ha-peers.conf 2>/dev/null | head -n1 | cut -d= -f2 | tr -d '[:space:]')
if [ -z "$STANDBY" ]; then
  echo "Standby HA peer IP not configured in /etc/alfred/ha-peers.conf (standby_ip=...)" >&2
  exit 2
fi
if [ "$#" -lt 1 ] || [ "$#" -gt 10 ]; then
  echo "Usage: alfred-ha-mirror /var/www/... (1-10 files)" >&2
  exit 2
fi
for fp in "$@"; do
  real=$(realpath -e "$fp")
  case "$real" in
    /var/www/*) ;;
    *) echo "Blocked path (only /var/www/* allowed): $fp" >&2; exit 3 ;;
  esac
  if [ ! -f "$real" ]; then
    echo "Not a regular file: $real" >&2
    exit 4
  fi
  owner=$(stat -c '%U:%G' "$real")
  mode=$(stat -c '%a' "$real")
  dir=$(dirname "$real")
  ssh -i "$KEY" -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=8 "root@$STANDBY" "mkdir -p '$dir'"
  scp -q -i "$KEY" -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=8 "$real" "root@$STANDBY:$real"
  ssh -i "$KEY" -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=8 "root@$STANDBY" "chown '$owner' '$real' 2>/dev/null || true; chmod '$mode' '$real'"
  echo "OK $real -> standby ($STANDBY) [$owner $mode]"
done
