#!/bin/bash
set -euo pipefail

# -------- Configuration --------
BCK_HOST="pbs.inxs.be"  # valeur par défaut si non définie par paramètre
PBS_DATASTORE="pbs-data"
PBS_USERNAME="bck_ops"
PBS_PASSWORD_FILE="/root/.pbs_password"
PBS_FINGERPRINT_FILE="/root/.pbs_fingerprint"
KUMA_BASE_URL="https://uptime.noxs.me/api/push"

# Load fingerprint from file
if [[ -f "$PBS_FINGERPRINT_FILE" ]]; then
  PBS_FINGERPRINT=$(<"$PBS_FINGERPRINT_FILE")
  export PBS_FINGERPRINT
else
  echo "❌ Fingerprint file not found: $PBS_FINGERPRINT_FILE"
  exit 3
fi

# Export password file
export PBS_PASSWORD_FILE

# -------- Usage Help --------
print_usage() {
  echo ""
  echo "Usage: bck_main.sh --src=<source_path> --dst=<backup_name> [--multi-src=<spec>] [--dry-run] [--exclude=pattern] [--kuma-key=...] [--pre-script=...] [--bck-host=...]"
  echo ""
  echo "Arguments:"
  echo "  --src <path> or --src=<path>          Source path to back up"
  echo "  --dst <name> or --dst=<name>          Backup name (.pxar archive)"
  echo "  --multi-src <specs>                   Backup multiple sources in 'name.pxar:/path' format, space-separated"
  echo "  --dry-run                             Simulate the backup"
  echo "  --exclude <pattern> or --exclude=...  Pattern to exclude (can repeat)"
  echo "  --kuma-key <key> or --kuma-key=...    Optional Uptime Kuma push key"
  echo "  --pre-script <path|command>           Optional command or script to run before the backup"
  echo "  --bck-host <host> or --bck-host=...   Override default PBS host (default: pbs.inxs.be)"
  echo "  --help                                Show this help message"
  echo ""
  echo "Environment files:"
  echo "  Password file:      $PBS_PASSWORD_FILE"
  echo "  Fingerprint file:   $PBS_FINGERPRINT_FILE"
  echo ""
}

# -------- Parse Arguments --------
SRC=""
DST=""
MULTI_SRC=""
DRY_RUN=""
KUMA_KEY=""
PRE_SCRIPT=""
EXCLUDES=()
BCK_HOST_OVERRIDE=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --src=*)
      SRC="${1#*=}"
      shift
      ;;
    --src)
      SRC="$2"
      shift 2
      ;;
    --dst=*)
      DST="${1#*=}"
      shift
      ;;
    --dst)
      DST="$2"
      shift 2
      ;;
    --multi-src=*)
      MULTI_SRC="${1#*=}"
      shift
      ;;
    --multi-src)
      MULTI_SRC="$2"
      shift 2
      ;;
    --dry-run)
      DRY_RUN="--dry-run=true"
      shift
      ;;
    --kuma-key=*)
      KUMA_KEY="${1#*=}"
      shift
      ;;
    --kuma-key)
      KUMA_KEY="$2"
      shift 2
      ;;
    --exclude=*)
      EXCLUDES+=("${1#*=}")
      shift
      ;;
    --exclude)
      EXCLUDES+=("$2")
      shift 2
      ;;
    --pre-script=*)
      PRE_SCRIPT="${1#*=}"
      shift
      ;;
    --pre-script)
      PRE_SCRIPT="$2"
      shift 2
      ;;
    --bck-host=*)
      BCK_HOST="${1#*=}"
      BCK_HOST_OVERRIDE="1"
      shift
      ;;
    --bck-host)
      BCK_HOST="$2"
      BCK_HOST_OVERRIDE="1"
      shift 2
      ;;
    --help|-h)
      print_usage
      exit 0
      ;;
    *)
      echo "❌ Unknown option: $1"
      print_usage
      exit 1
      ;;
  esac
done

# -------- Validate Arguments --------
if [[ -n "$MULTI_SRC" ]]; then
  echo "🔁 Using multi-src mode: $MULTI_SRC"
elif [[ -n "$SRC" && -n "$DST" ]]; then
  BACKUP_SPEC="${DST}.pxar:${SRC}"
else
  echo "❌ Error: You must provide either --src and --dst, or --multi-src."
  print_usage
  exit 1
fi

# -------- Detect if we are remote (only if not overridden) --------
if [[ -z "$BCK_HOST_OVERRIDE" ]]; then
  is_remote_via_tailscale() {
    local ts_ips
    ts_ips=$(tailscale ip -4 2>/dev/null || true)
    while IFS= read -r ip; do
      if [[ "$ip" =~ ^100\.100\.10\. ]]; then
        return 1  # LAN IP present
      fi
    done <<< "$ts_ips"
    return 0  # no LAN IP -> remote
  }

  if is_remote_via_tailscale; then
    echo "🌍 No local Tailscale IP in 100.100.10.0/24 — using remote PBS endpoint"
    BCK_HOST="pbs.inxs.me"
  else
    echo "🏠 Local Tailscale IP detected — using default PBS endpoint"
  fi
fi

# -------- Final PBS_REPOSITORY setup --------
if [[ "$(hostname)" == "k2t" ]]; then
  PBS_REPOSITORY="${PBS_USERNAME}@pbs@localhost:${PBS_DATASTORE}"
else
  PBS_REPOSITORY="${PBS_USERNAME}@pbs@${BCK_HOST}:${PBS_DATASTORE}"
fi

export PBS_REPOSITORY

echo "🚀 Starting backup..."
[[ -n "$DRY_RUN" ]] && echo "ℹ️ Running in dry-run mode."
echo "ℹ️ PBS Host: $BCK_HOST"

# -------- Check for Raspberry Pi --------
is_raspberry_pi() {
  grep -q "Raspberry Pi" /proc/device-tree/model 2>/dev/null
}

# -------- Build exclude options --------
EXCLUDE_OPTS=""
for pattern in "${EXCLUDES[@]}"; do
  EXCLUDE_OPTS+=" --exclude \"$pattern\""
done

# -------- Construct Backup Command --------
if [[ -n "$MULTI_SRC" ]]; then
  BACKUP_SPEC=$MULTI_SRC
else
  BACKUP_SPEC="${DST}.pxar:${SRC}"
fi

BACKUP_CMD="backup ${BACKUP_SPEC} --backup-id \"$(hostname)\" ${DRY_RUN} ${EXCLUDE_OPTS}"

if ! is_raspberry_pi; then
  BIN_LOCATION="/usr/bin/proxmox-backup-client"
  BACKUP_CMD="$BIN_LOCATION $BACKUP_CMD"
  BACKUP_CMD+=" --change-detection-mode=metadata"
  echo "🚀 Host is not a Raspberry Pi..."
else
  BIN_LOCATION="/usr/local/bin/pbs_client/proxmox-backup-client"
  BACKUP_CMD="$BIN_LOCATION $BACKUP_CMD"
  echo "🚀 Host is a Raspberry Pi..."
fi

# -------- Run Pre-script if defined --------
if [[ -n "$PRE_SCRIPT" ]]; then
  echo "⚙️ Running pre-script: $PRE_SCRIPT"
  if [[ -x "$PRE_SCRIPT" ]]; then
    "$PRE_SCRIPT"
  else
    bash -c "$PRE_SCRIPT"
  fi
  PRE_RESULT=$?
  if [[ $PRE_RESULT -ne 0 ]]; then
    echo "❌ Pre-script failed with exit code $PRE_RESULT. Aborting backup."
    exit 2
  fi
fi

# -------- Run Backup --------
echo "📦 Running: $BACKUP_CMD"
eval "$BACKUP_CMD"
RESULT=$?

# -------- Result Handling + Optional Uptime Kuma Push --------
if [[ $RESULT -eq 0 ]]; then
  echo "✅ Backup successful."
  if [[ -n "$KUMA_KEY" ]]; then
    curl -fsS --max-time 10 "${KUMA_BASE_URL}/${KUMA_KEY}?status=up&msg=OK&ping=" || \
      echo "⚠️ Failed to ping Uptime Kuma success URL."
  fi
  exit 0
else
  echo "❌ Backup failed!"
  if [[ -n "$KUMA_KEY" ]]; then
    curl -fsS --max-time 10 "${KUMA_BASE_URL}/${KUMA_KEY}?status=down&msg=Backup+failed&ping=" || \
      echo "⚠️ Failed to ping Uptime Kuma failure URL."
  fi
  exit 1
fi