#!/usr/bin/env bash
# Nightly Gitea backup into a restic repository on the portable HDD (the backup drive).
# Installed as /usr/local/sbin/gitea-backup, run as root by gitea-backup.service.
# Setup and operation: OKF/guides/11-backup-automated.md
#
#   gitea-backup init            create the restic repository on the backup drive (once)
#   gitea-backup run             stop Gitea, snapshot gitea-data, start Gitea, prune;
#                                full check + weekly report mail on CHECK_WEEKDAY
#   gitea-backup snapshots       list snapshots
#   gitea-backup check           full restic check (reads every pack)
#   gitea-backup restore-test    restore latest snapshot to scratch, verify, boot a throwaway Gitea
#   gitea-backup test-mail       send a test mail to MAILTO
#   gitea-backup notify-failure  mail the journal of the last failed run (used by OnFailure=)
set -euo pipefail

ENV_FILE=/etc/gitea-backup/env
[[ -r $ENV_FILE ]] || { echo "ERROR: missing $ENV_FILE (run as root?)" >&2; exit 1; }
# shellcheck source=/dev/null
. "$ENV_FILE"
LABEL=${LABEL:-BACKUP}
MOUNT=${MOUNT:-/mnt/backup}
STACK=${STACK:-/home/admin/mithlond}
CHECK_WEEKDAY=${CHECK_WEEKDAY:-7}   # ISO weekday (7 = Sunday) for full check + report mail
: "${RESTIC_REPOSITORY:?set in $ENV_FILE}" "${RESTIC_PASSWORD_FILE:?set in $ENV_FILE}" "${MAILTO:?set in $ENV_FILE}"
export RESTIC_REPOSITORY RESTIC_PASSWORD_FILE
export RESTIC_CACHE_DIR=${RESTIC_CACHE_DIR:-/var/cache/restic}
KEEP=(--keep-daily 7 --keep-weekly 4 --keep-monthly 12)

SCRATCH=/var/tmp/gitea-restore-test   # on disk: /tmp is a 1.5G tmpfs
TEST_CONTAINER=gitea-restore-test
LOCK=/run/gitea-backup.lock

mounted_by_us=0
gitea_stopped=0
scratch_ours=0

log() { printf '==> %s\n' "$*"; }
die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
usage() { sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//'; exit 2; }

# Whatever fails: Gitea back up, no throwaway container, no scratch copy of the
# host keys, and the backup drive unmounted (a mounted NTFS volume that loses power comes
# back dirty, and every later run fails until ntfsfix).
cleanup() {
  local rc=$?
  if (( gitea_stopped )); then
    echo "==> restarting gitea (exit path)"
    docker start gitea >/dev/null || echo "!! gitea did not start — run: docker start gitea" >&2
  fi
  docker rm -f "$TEST_CONTAINER" >/dev/null 2>&1 || true
  if (( scratch_ours )); then rm -rf "$SCRATCH"; fi
  if (( mounted_by_us )); then
    cd /
    sync
    if umount "$MOUNT"; then
      echo "==> unmounted $MOUNT"
    elif umount -l "$MOUNT"; then   # device vanished mid-run: detach the dead mount
      echo "!! $MOUNT detached lazily — device was gone" >&2
    else
      echo "!! umount $MOUNT failed" >&2
    fi
  fi
  exit "$rc"
}
trap cleanup EXIT

need_root() { (( EUID == 0 )) || die "run as root: sudo gitea-backup $*"; }

lock() {
  exec 9>"$LOCK"
  flock -n 9 || die "another gitea-backup is already running"
}

mount_hdd() {
  local dev=/dev/disk/by-label/$LABEL
  [[ -e $dev ]] || die "HDD '$LABEL' not attached"
  dev=$(readlink -f "$dev")
  if findmnt -rn "$MOUNT" >/dev/null; then
    [[ $(findmnt -rno SOURCE "$MOUNT") == "$dev" ]] || die "$MOUNT holds something other than $LABEL"
    # Same device name but no longer readable = a dead mount left by an
    # unplug (the replugged drive can come back under the same name).
    if ! stat -t "$MOUNT/." >/dev/null 2>&1 || ! ls "$MOUNT" >/dev/null 2>&1; then
      echo "!! $MOUNT is a dead mount — detaching and remounting" >&2
      umount -l "$MOUNT"
    else
      return   # mounted by someone else (e.g. scripts/backup.sh) — leave it mounted
    fi
  fi
  mkdir -p "$MOUNT"
  if ! mount -t ntfs3 "$dev" "$MOUNT"; then
    # Unattended: never repair or force. A human runs ntfsfix (OKF/guides/10 §2).
    dmesg | tail -n 20 | grep -q 'volume is dirty' \
      && die "$LABEL is dirty — run by hand: ntfsfix -n /dev/disk/by-label/$LABEL, then ntfsfix -d (OKF/guides/10 §2)"
    die "mount $dev failed — see dmesg"
  fi
  mounted_by_us=1
}

repo_ok() {
  restic cat config >/dev/null 2>&1 || die "no restic repo at $RESTIC_REPOSITORY — run: gitea-backup init"
  # A run cut off mid-write (the backup drive pulled, power cut) can leave its lock on
  # disk, and every later run would fail on it. Safe to clear here: flock
  # guarantees no other gitea-backup on this host, and this host is the
  # repo's only user. Without --remove-all, unlock drops only locks whose
  # process is dead.
  restic unlock
}

mail_report() {   # subject, body on stdin
  { printf 'To: %s\nSubject: [mithlond] %s\n\n' "$MAILTO" "$1"; cat; } | msmtp "$MAILTO"
}

cmd_init() {
  need_root init; lock; mount_hdd
  if restic cat config >/dev/null 2>&1; then die "repo already exists at $RESTIC_REPOSITORY"; fi
  [[ -s $RESTIC_PASSWORD_FILE ]] || die "empty or missing $RESTIC_PASSWORD_FILE"
  mkdir -p "$RESTIC_REPOSITORY"
  restic init
}

cmd_run() {
  need_root run; lock; mount_hdd; repo_ok
  docker inspect gitea >/dev/null 2>&1 || die "no gitea container"

  log "stopping gitea (SQLite must not be written mid-snapshot)"
  gitea_stopped=1
  docker stop gitea >/dev/null
  local t0=$SECONDS
  # restic stores owners and modes itself, so NTFS losing them does not matter.
  restic backup --host mithlond --tag gitea "$STACK/gitea-data"
  docker start gitea >/dev/null
  gitea_stopped=0
  log "gitea down $((SECONDS - t0))s"

  log "pruning (${KEEP[*]})"
  restic forget --prune --tag gitea "${KEEP[@]}"

  if [[ $(date +%u) == "$CHECK_WEEKDAY" ]]; then
    log "weekly full check"
    restic check --read-data
    # Proof of life: no Sunday mail means the timer itself stopped firing.
    restic snapshots --compact | mail_report "weekly backup report: OK (check --read-data passed)"
  fi
}

cmd_restore_test() {
  need_root restore-test; lock; mount_hdd; repo_ok
  [[ ! -e $SCRATCH ]] || die "$SCRATCH exists — inspect and remove it first"
  mkdir -p "$SCRATCH"
  scratch_ours=1
  log "restoring latest snapshot to $SCRATCH"
  restic restore latest --tag gitea --target "$SCRATCH"
  local r=$SCRATCH$STACK/gitea-data
  [[ -f $r/gitea/gitea.db && -d $r/git/repositories ]] || die "restore lacks gitea.db or repositories"
  [[ $(stat -c '%U:%G %a' "$r/ssh") == "root:root 700" ]] || die "gitea-data/ssh lost root:root 700"
  echo "gitea-data/ssh/ root:root 700"

  log "SQLite integrity"
  local ok
  ok=$(sqlite3 -readonly "$r/gitea/gitea.db" 'PRAGMA integrity_check;')
  [[ $ok == ok ]] || die "gitea.db integrity_check: $ok"
  echo "integrity_check: ok"
  sqlite3 -readonly -list -noheader "$r/gitea/gitea.db" \
    "select 'users=' || count(*) from user; select 'repos=' || count(*) from repository;"

  log "git fsck every repo (inside the gitea image)"
  local img
  img=$(docker inspect -f '{{.Config.Image}}' gitea)
  docker run --rm --user 1000:1000 --entrypoint sh -v "$r/git/repositories:/r:ro" "$img" -c '
    cd /r; fail=0
    for d in */*.git; do
      if out=$(git -c safe.directory="*" --git-dir="$d" fsck --no-progress --no-dangling 2>&1); then
        printf "%-36s %s\n" "$d" "${out:-OK}"
      else
        printf "%-36s FAILED\n%s\n" "$d" "$out"; fail=1
      fi
    done
    exit $fail' || die "git fsck failed on at least one repo"

  log "booting a throwaway Gitea on the restore (--network none)"
  docker run -d --rm --name "$TEST_CONTAINER" --network none \
    -e USER_UID=1000 -e USER_GID=1000 -v "$r:/data" "$img" >/dev/null
  local i version=
  for i in $(seq 1 30); do
    version=$(docker exec "$TEST_CONTAINER" wget -qO- http://127.0.0.1:3000/api/v1/version 2>/dev/null) && break
    sleep 2
  done
  [[ -n $version ]] || { docker logs --tail 20 "$TEST_CONTAINER"; die "restored Gitea did not answer within 60s"; }
  echo "restored Gitea answers: $version"
  docker exec "$TEST_CONTAINER" su git -c 'gitea admin user list'
  docker stop "$TEST_CONTAINER" >/dev/null
  log "RESTORE TEST PASSED"
}

cmd_notify_failure() {
  # systemd hands OnFailure= units the failed run's invocation ID; scope the
  # journal to exactly that run, falling back to the tail when run by hand.
  local sel=(-u gitea-backup.service -n 80)
  [[ -n ${MONITOR_INVOCATION_ID:-} ]] && sel=(_SYSTEMD_INVOCATION_ID="$MONITOR_INVOCATION_ID")
  journalctl "${sel[@]}" --no-pager -o short-iso \
    | mail_report "gitea-backup FAILED on $(uname -n) (${MONITOR_SERVICE_RESULT:-manual})"
}

case ${1:-} in
  init)           cmd_init ;;
  run)            cmd_run ;;
  snapshots)      need_root snapshots; lock; mount_hdd; repo_ok; restic snapshots ;;
  check)          need_root check; lock; mount_hdd; repo_ok; restic check --read-data ;;
  restore-test)   cmd_restore_test ;;
  test-mail)      echo "Test from gitea-backup on $(uname -n) at $(date -Is)." | mail_report "gitea-backup test mail" ;;
  notify-failure) cmd_notify_failure ;;
  *)              usage ;;
esac
