#!/bin/bash
set -euo pipefail

die() {
  echo >&2 "$@"
  exit 1
}

DEFAULT_KEEP=14

valid_keep() {
  [[ "$1" =~ ^[0-9]+$ ]]
}

parse_args() {
  YES=0
  KEEP=""
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --yes)
        YES=1
        shift
        ;;
      --keep)
        [[ $# -ge 2 ]] || die "Missing value for --keep"
        valid_keep "$2" || die "Invalid --keep value: '$2' (expected a whole number, 0 = keep all)"
        KEEP="$2"
        shift 2
        ;;
      *)
        die "Unknown argument: $1"
        ;;
    esac
  done
}

check_root() {
  if [[ "$(id -u)" -ne 0 ]]; then
    die "This script must be run as root"
  fi
}

DEST_PATH="/usr/local/bin/as-backup.sh"
SYSTEMD_DIR="${SYSTEMD_DIR:-/etc/systemd/system}"
CRON_FILE="${CRON_FILE:-/etc/cron.d/as-backup}"

# schedule_command KEEP: the command the timer/cron runs. KEEP=0 keeps all scheduled backups.
schedule_command() {
  if [[ "$1" -gt 0 ]]; then
    echo "$DEST_PATH --auto --keep $1"
  else
    echo "$DEST_PATH --auto"
  fi
}

download_script() {
  local dest_path="${DEST_PATH}"
  local url="https://as-backup.devopenvpn.net/as-backup.sh"

  if [[ -f "$dest_path" && "$YES" -eq 0 ]]; then
    read -p "Overwrite existing file at $dest_path? [y/N] " answer < /dev/tty
    if [[ "$answer" != "y" ]]; then
      echo "Installation cancelled."
      exit 0
    fi
  fi
  
  echo "Downloading script from $url..."
  curl -fsSL "$url" -o "$dest_path"
  chmod +x "$dest_path"
  echo "Script installed at $dest_path"
}

detect_scheduler() {
  SCHEDULER=""
  if command -v systemctl &>/dev/null && systemctl --version &>/dev/null; then
    SCHEDULER="systemd"
  elif command -v cron &>/dev/null || command -v crond &>/dev/null; then
    SCHEDULER="cron"
  else
    die "Could not find a valid scheduler (systemd or cron)."
  fi
}

setup_systemd() {
  local frequency="$1"
  local keep="$2"
  local on_calendar

  case "$frequency" in
    hourly) on_calendar="hourly" ;;
    daily) on_calendar="daily" ;;
    weekly) on_calendar="weekly" ;;
    *) die "Invalid frequency for systemd: $frequency" ;;
  esac

  local service_file="$SYSTEMD_DIR/as-backup.service"
  local timer_file="$SYSTEMD_DIR/as-backup.timer"

  if [[ -f "$timer_file" && "$YES" -eq 0 ]]; then
    read -p "Overwrite existing systemd timer? [y/N] " answer < /dev/tty
    if [[ "$answer" != "y" ]]; then
      echo "Scheduler setup cancelled."
      return
    fi
  fi

cat > "$service_file" <<EOF
[Unit]
Description=Access Server Backup
[Service]
ExecStart=$(schedule_command "$keep")
EOF

cat > "$timer_file" <<EOF
[Unit]
Description=Run Access Server Backup periodically
[Timer]
OnCalendar=$on_calendar
Persistent=true
[Install]
WantedBy=timers.target
EOF

  systemctl daemon-reload
  systemctl enable --now as-backup.timer
  echo "systemd timer configured."
}

setup_cron() {
    local frequency="$1"
    local keep="$2"
    local cron_expr
    
    case "$frequency" in
        hourly) cron_expr="0 * * * *" ;;
        daily) cron_expr="0 2 * * *" ;;
        weekly) cron_expr="0 2 * * 0" ;;
        *) die "Invalid frequency for cron: $frequency" ;;
    esac

    local cron_file="$CRON_FILE"
    
    if [[ -f "$cron_file" && "$YES" -eq 0 ]]; then
        read -p "Overwrite existing cron job? [y/N] " answer < /dev/tty
        if [[ "$answer" != "y" ]]; then
            echo "Scheduler setup cancelled."
            return
        fi
    fi

    echo "$cron_expr root $(schedule_command "$keep")" > "$cron_file"
    echo "cron job configured."
}

ask_schedule() {
  if [[ "$YES" -eq 1 ]]; then
    echo "daily"
    return
  fi

  read -p "Do you want to schedule regular backups? [Y/n] " schedule_answer < "${TTY_DEVICE:-/dev/tty}"
  if [[ "$schedule_answer" =~ ^[nN] ]]; then
    return
  fi

  read -p "How often? h=hourly d=daily w=weekly (or 1/2/3) [d]: " freq_answer < "${TTY_DEVICE:-/dev/tty}"
  case "$freq_answer" in
    h|H|1|hourly)
      echo "hourly"
      ;;
    d|D|2|daily)
      echo "daily"
      ;;
    w|W|3|weekly)
      echo "weekly"
      ;;
    *)
      echo "daily"
      ;;
  esac
}

# ask_keep: how many scheduled backups to keep (0 = all). --keep wins; --yes uses the default.
ask_keep() {
  if [[ -n "$KEEP" ]]; then
    echo "$KEEP"
    return
  fi
  if [[ "$YES" -eq 1 ]]; then
    echo "$DEFAULT_KEEP"
    return
  fi

  local keep_answer=""
  read -p "Keep how many scheduled backups? (0 = keep all) [$DEFAULT_KEEP]: " keep_answer < "${TTY_DEVICE:-/dev/tty}"
  if [[ -z "$keep_answer" ]]; then
    echo "$DEFAULT_KEEP"
    return
  fi
  valid_keep "$keep_answer" || die "Invalid number: '$keep_answer'"
  echo "$keep_answer"
}

main() {
  parse_args "$@"
  check_root
  download_script
  
  local frequency
  frequency=$(ask_schedule)

  if [[ -n "$frequency" ]]; then
    local keep
    keep=$(ask_keep)
    detect_scheduler
    case "$SCHEDULER" in
      systemd) setup_systemd "$frequency" "$keep" ;;
      cron) setup_cron "$frequency" "$keep" ;;
    esac
    if [[ "$keep" -gt 0 ]]; then
      echo "Scheduled backups: $frequency, keeping the newest $keep (manual backups are never deleted)."
    else
      echo "Scheduled backups: $frequency, keeping all."
    fi
  fi
  
  echo "Installation complete."
}

# Guard against execution when sourced for tests
if [[ "${INSTALL_TESTING:-}" != "1" ]]; then
  main "$@"
fi
