#!/usr/bin/env bash
# ---------------------------------------------------------------------------
#  File-sync helper for ket.swallow-grue.ts.net
#
#  – Synchronise des fichiers depuis **ket** vers la machine locale.
#  – Si exécuté sur ket, rsync effectue une copie locale.
#  – Chaque ligne du fichier de conf peut cibler des machines spécifiques.
# ---------------------------------------------------------------------------

set -euo pipefail

# --- ROOT CHECK -----------------------------------------------------------
if command -v require_root &>/dev/null; then
  require_root
elif (( EUID != 0 )); then
  echo "❌ Run this script as root." >&2
  exit 1
fi

# --- CONSTANTS ------------------------------------------------------------
REMOTE_USER="root"
REMOTE_HOST="ket.swallow-grue.ts.net"
SSH_OPTS=(-o StrictHostKeyChecking=no)
LOG_FILE="/var/log/system_sync_files.log"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SYNC_ITEMS_FILE="$SCRIPT_DIR/system_sync_files.conf"

# --- VALIDATE CONFIG FILE -------------------------------------------------
if [[ ! -f "$SYNC_ITEMS_FILE" ]]; then
  echo "❌ Missing SYNC_ITEMS file: $SYNC_ITEMS_FILE" >&2
  exit 1
fi

# --- HELPERS --------------------------------------------------------------
log() {
  printf '[%s] %s\n' "$(date --iso-8601=seconds)" "$*" | tee -a "$LOG_FILE"
}

on_remote_host() {
  local here; here=$(hostname -f)
  [[ "$here" == "$REMOTE_HOST" || "$here" == "${REMOTE_HOST%%.*}" ]]
}

this_host() {
  hostname -f
}

should_sync_for_host() {
  local line_hosts=$1
  local here; here="$(this_host)"

  [[ "$line_hosts" == "all" ]] && return 0

  IFS=',' read -ra HOST_LIST <<< "$line_hosts"
  for h in "${HOST_LIST[@]}"; do
    if [[ "$h" == "$here" || "$h" == "${here%%.*}" ]]; then
      return 0
    fi
  done

  return 1
}

exec_sync() {
  local src=$1 dest=$2 mode=$3 owner=$4
  log "🔄 Syncing $src → $dest (mode=$mode owner=$owner)"

  local cmd
  if on_remote_host; then
    cmd=(rsync -auv --chmod="$mode" --chown="$owner" "$src" "$dest")
  else
    cmd=(rsync -auv --chmod="$mode" --chown="$owner" \
      -e "ssh ${SSH_OPTS[*]}" \
      "${REMOTE_USER}@${REMOTE_HOST}:${src}" "$dest")
  fi

  if "${cmd[@]}" >>"$LOG_FILE" 2>&1; then
    log "✅ Success: $src"
    ((++SUCCESS_COUNT))
  else
    log "❌ Failed: $src"
    ((++FAIL_COUNT))
  fi
}

# --- MAIN ------------------------------------------------------------------
log "📁 Starting sync from $REMOTE_HOST"
log "📍 Local hostname: $(this_host)"
log "📝 Reading config: $SYNC_ITEMS_FILE"

SUCCESS_COUNT=0
FAIL_COUNT=0
LINE_NUM=0

while IFS='|' read -r src dest mode owner hosts || [[ -n "$src" ]]; do
  ((++LINE_NUM))
  # Nettoyage
  src="$(echo "$src" | xargs)"
  [[ -z "$src" || "${src:0:1}" == "#" ]] && continue

  # Vérifie au moins 4 champs
  if [[ -z "$dest" || -z "$mode" || -z "$owner" ]]; then
    log "⚠️  Skipping line $LINE_NUM: invalid format (need at least 4 fields)"
    ((++FAIL_COUNT))
    continue
  fi

  # Si hosts est vide ou manquant, fallback à "all"
  hosts="$(echo "${hosts:-}" | xargs)"
  [[ -z "$hosts" ]] && hosts="all"

  if should_sync_for_host "$hosts"; then
    exec_sync "$src" "$dest" "$mode" "$owner"
  else
    log "⏩ Skipping $src → $dest (not for this host: $hosts)"
  fi
done < "$SYNC_ITEMS_FILE"

# --- SUMMARY --------------------------------------------------------------
log "✅ Total success: $SUCCESS_COUNT"
log "❌ Total failed:  $FAIL_COUNT"
exit $((FAIL_COUNT))