#!/usr/bin/env bash
# Alfred HA Webroot Incremental Mirror (15-minute timer)
# Reads standby_ip from /etc/alfred/ha-peers.conf and optional paths from /etc/alfred/ha-websync.dirs.
# Zero hardcoded IPs, domains, or usernames.
set -euo pipefail

CONF="/etc/alfred/ha-peers.conf"
DIRS_CONF="/etc/alfred/ha-websync.dirs"
KEY="/etc/alfred/ha-standby-id_ed25519"
LOCK="/run/alfred-ha-websync.lock"

if [[ ! -f "$CONF" || ! -f "$KEY" ]]; then
  exit 0
fi

STANDBY_IP="$(awk -F= '/^standby_ip=/{print $2}' "$CONF" | tr -d ' \t\r\n')"
if [[ -z "$STANDBY_IP" || ! "$STANDBY_IP" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  exit 0
fi

exec 9>"$LOCK"
if ! flock -n 9; then
  exit 0
fi

SSH_CMD="ssh -i $KEY -o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new"

sync_tree() {
  local src="${1%/}/"
  if [[ -d "$src" ]]; then
    $SSH_CMD -n "root@${STANDBY_IP}" "mkdir -p '$src'"
    rsync -az --max-size=40m \
      --exclude='.git/' \
      --exclude='cache/' \
      --exclude='tmp/' \
      --exclude='logs/' \
      --exclude='sessions/' \
      --exclude='uploads/' \
      --exclude='downloads/' \
      --exclude='iso/' \
      --exclude='ota/' \
      --exclude='*.iso' \
      --exclude='*.tar.gz' \
      --exclude='*.zip' \
      --exclude='*.log' \
      --exclude='*.bak*' \
      --exclude='includes/config.local.php' \
      --exclude='api/config.php' \
      -e "$SSH_CMD" \
      "$src" "root@${STANDBY_IP}:${src}"
  fi
}

if [[ -f "$DIRS_CONF" ]]; then
  while IFS= read -r line; do
    line="${line%%#*}"
    line="$(echo "$line" | xargs)"
    [[ -n "$line" ]] && sync_tree "$line"
  done < "$DIRS_CONF"
else
  shopt -s nullglob
  for d in /var/www/*/web /home/*/domains/*/public_html; do
    sync_tree "$d"
  done
fi

echo "[alfred-ha-websync] Synced webroots to standby (${STANDBY_IP}) at $(date -u +%Y-%m-%dT%H:%M:%SZ)"
