#!/usr/bin/env bash
set -euo pipefail

readonly SCRIPT_NAME="${0##*/}"
readonly BACKUP_URL='https://opengist.resetrix.work/weehong/2de15ba0106a475fa41215159203a63b/raw/HEAD/backup-thunderbird-to-synology.sh'
readonly CRON_MARKER='# thunderbird-synology-backup'
readonly CRON_ENTRY="0 * * * * /usr/bin/bash -o pipefail -c '/usr/bin/curl --proto \"=https\" --tlsv1.2 -fsSL --max-time 60 \"$BACKUP_URL\" | /usr/bin/bash' >> \"\$HOME/.local/state/thunderbird-cron.log\" 2>&1 $CRON_MARKER"
DRY_RUN=0

usage() {
  cat <<EOF
Usage: $SCRIPT_NAME [--dry-run] [--help]

Installs an hourly user cron job that fetches and executes the hosted
Thunderbird-to-Synology backup script without storing the script locally.

Options:
  --dry-run    Print the cron entry without installing it.
  --help, -h   Show this help.
EOF
}

die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }

while (( $# )); do
  case "$1" in
    --dry-run) DRY_RUN=1 ;;
    -h|--help) usage; exit 0 ;;
    *) die "Unknown argument: $1 (try --help)" ;;
  esac
  shift
done

(( EUID != 0 )) || die "Do not run as root. Run as your normal user."

for tool in /usr/bin/bash /usr/bin/curl crontab grep; do
  if [[ "$tool" == /* ]]; then
    [[ -x "$tool" ]] || die "Missing required tool: $tool"
  else
    command -v "$tool" >/dev/null 2>&1 || die "Missing required tool: $tool"
  fi
done

if (( DRY_RUN )); then
  printf '%s\n' "$CRON_ENTRY"
  exit 0
fi

mkdir -p "$HOME/.local/state"

current_crontab="$(crontab -l 2>/dev/null || true)"
filtered_crontab="$(printf '%s\n' "$current_crontab" | grep -Fv -e "$CRON_MARKER" -e 'backup-thunderbird-to-synology.sh' || true)"

if [[ -n "$filtered_crontab" ]]; then
  printf '%s\n%s\n' "$filtered_crontab" "$CRON_ENTRY" | crontab -
else
  printf '%s\n' "$CRON_ENTRY" | crontab -
fi

installed_count="$(crontab -l | grep -Fxc "$CRON_ENTRY" || true)"
[[ "$installed_count" == 1 ]] || die "Unable to verify the hourly cron entry."

printf 'Installed hourly Thunderbird backup cron job.\n'
printf '%s\n' "$CRON_ENTRY"
