#!/bin/bash
# ctg-restic: one restic wrapper for every Linux host (owner standard 2026-10-30: encrypted, B2, 30 days).
#   ctg-restic backup   daily; runs /etc/ctg-backup/pre.sh first if present, then backs up the paths file
#   ctg-restic prune    weekly; forget --keep-within 30d --prune
#   ctg-restic check    monthly; check --read-data-subset=5%
#   ctg-restic <other>  passed through to restic (snapshots, restore, ...)
# Config dir /etc/ctg-backup (root:root 0700): env (RESTIC_REPOSITORY, AWS_*/B2_* credentials, RESTIC_PASSWORD_FILE),
# paths (one path per line), excludes (restic --exclude-file), optional pre.sh / post.sh.
# State dir /var/lib/ctg-backup: last-backup-ok, last-prune-ok, last-check-ok, last-check-fail (epoch seconds).
set -uo pipefail
CONF=${CTG_BACKUP_CONF:-/etc/ctg-backup}
STATE=${CTG_BACKUP_STATE:-/var/lib/ctg-backup}
KEEP=${CTG_KEEP_WITHIN:-30d}
# Backup/prune/check take the repo lock (prune/check exclusive); a timer that fires while another run holds it must wait, not fail.
RETRY_LOCK=${CTG_RETRY_LOCK:-3h}
# Generation marker: every run of THIS wrapper carries it (and passes it to restic and the hooks). A process without it that is
# running a repo-mutating restic command for this config is a pre-lock ("legacy") run, e.g. a multi-day Time Machine backup that was
# started before the flock existed. A flock cannot exclude such a run, so we look for it (legacy_active) and wait for it.
# /proc/PID/environ shows only the environment a process was exec'd with, so the wrapper re-execs itself once to carry the marker too.
[ "${CTG_RESTIC_WRAPPER:-}" = 2 ] || exec env CTG_RESTIC_WRAPPER=2 "$0" "$@"
set -a; . "$CONF/env"; set +a
export HOME=${HOME:-/root}
mkdir -p "$STATE"
cmd=${1:-backup}; [ $# -gt 0 ] && shift
now() { date +%s; }
secs() { case "$1" in *d) echo $(( ${1%d} * 86400 ));; *h) echo $(( ${1%h} * 3600 ));; *m) echo $(( ${1%m} * 60 ));; *s) echo "${1%s}";; *) echo "$1";; esac; }
LOCK=$STATE/ctg-restic.lock
POLL=${CTG_LOCK_POLL:-15}
MUTATING_RE='^(backup|forget|prune|check|rebuild-index|repair|rewrite|tag|copy|migrate|init|key|recover)$'

# Print "<pid> <what>" for every process, other than us and our ancestors, that is running a repo-mutating restic command against
# this config's repository without the generation marker (pre-lock wrapper or bare restic). Needs root to read other environments.
legacy_active() {
  local anc=" " q=$$ pp d pid env sub conf repo first arg found=1
  local -a argv
  while [ "$q" -gt 1 ]; do anc="$anc$q "; pp=$(awk '{print $4}' "/proc/$q/stat" 2>/dev/null) || break; [ -z "$pp" ] && break; q=$pp; done
  for d in /proc/[0-9]*; do
    pid=${d#/proc/}
    case "$anc" in *" $pid "*) continue;; esac
    { mapfile -d '' -t argv < "$d/cmdline"; } 2>/dev/null || continue
    [ ${#argv[@]} -gt 0 ] || continue
    first=${argv[0]##*/}
    # a script named restic run through its interpreter (test doubles) counts like the binary
    if [[ $first =~ ^(bash|sh|dash)$ ]] && [[ ${argv[1]:-} == */restic ]]; then argv=("${argv[@]:1}"); first=restic; fi
    if [ "$first" = restic ]; then
      sub=""; for arg in "${argv[@]:1}"; do case "$arg" in -*) ;; *) sub=$arg; break;; esac; done
      [[ $sub =~ $MUTATING_RE ]] || continue
      env=$({ tr '\0' '\n' < "$d/environ"; } 2>/dev/null) || { echo "$pid $first $sub (environment unreadable: assumed active)"; found=0; continue; }
      case $'\n'"$env"$'\n' in *$'\nCTG_RESTIC_WRAPPER=2\n'*) continue;; esac
      repo=$(printf '%s\n' "$env" | sed -n 's/^RESTIC_REPOSITORY=//p' | head -1)
      [ -n "$repo" ] && [ "$repo" = "${RESTIC_REPOSITORY:-}" ] || continue
      echo "$pid restic $sub"; found=0
    elif [[ $first =~ ^(bash|sh|dash)$ ]] && [[ ${argv[1]:-} == */ctg-restic ]]; then
      sub=${argv[2]:-backup}
      [[ $sub =~ $MUTATING_RE ]] || continue
      env=$({ tr '\0' '\n' < "$d/environ"; } 2>/dev/null) || { echo "$pid $first $sub (environment unreadable: assumed active)"; found=0; continue; }
      case $'\n'"$env"$'\n' in *$'\nCTG_RESTIC_WRAPPER=2\n'*) continue;; esac
      conf=$(printf '%s\n' "$env" | sed -n 's/^CTG_BACKUP_CONF=//p' | head -1); conf=${conf:-/etc/ctg-backup}
      [ "$conf" = "$CONF" ] || continue
      echo "$pid ctg-restic $sub (pre-lock wrapper)"; found=0
    fi
  done
  return $found
}

# Wait (bounded by $RETRY_LOCK) for a pre-lock run to finish. We never signal it.
wait_legacy() {
  local limit start out warned=""; limit=$(secs "$RETRY_LOCK"); start=$(now)
  while out=$(legacy_active); do
    if [ $(( $(now) - start )) -ge "$limit" ]; then
      echo "ctg-restic: $cmd gave up after $RETRY_LOCK: a pre-lock run is still active: $out" >&2; return 75
    fi
    [ -n "$warned" ] || { echo "ctg-restic: waiting for a running pre-lock run to finish (never interrupted): $out" >&2; warned=1; }
    sleep "$POLL"
  done
}

case "$cmd" in
  # Hook guard (pre.sh/post.sh): ok when called by a wrapper run that holds the lock; otherwise refuse while anything else
  # (lock holder or pre-lock run) is active, so a hand-run hook can never destroy a snapshot a live backup is reading.
  hook-guard)
    if [ "${CTG_RESTIC_LOCKED:-}" = 1 ] && [ -n "${CTG_RESTIC_LOCK_PID:-}" ] && tr '\0' ' ' < "/proc/$CTG_RESTIC_LOCK_PID/cmdline" 2>/dev/null | grep -q ctg-restic; then exit 0; fi
    ( exec 8>>"$LOCK"; flock -n 8 ) || { echo "ctg-restic: hook refused: another ctg-restic run holds $LOCK" >&2; exit 75; }
    if out=$(legacy_active); then echo "ctg-restic: hook refused: a pre-lock run is active: $out" >&2; exit 75; fi
    exit 0 ;;
  busy) if out=$(legacy_active); then echo "$out"; exit 0; fi
        ( exec 8>>"$LOCK"; flock -n 8 ) || { echo "lock held"; exit 0; }; exit 1 ;;
  snapshots|ls|find|stats|cat|diff|dump|restore|list|mount|version|help|generate|cache|features|options) exec restic "$cmd" "$@" ;;
esac

# Everything below mutates (or may mutate) the repository: one run at a time per config, hooks included.
if [ "${CTG_RESTIC_LOCKED:-}" != 1 ]; then
  command -v flock >/dev/null || { echo "ctg-restic: flock missing, refusing to run unserialized" >&2; exit 70; }
  exec 9>>"$LOCK"
  if ! flock -w "$(secs "$RETRY_LOCK")" 9; then echo "ctg-restic: $cmd gave up after $RETRY_LOCK: another ctg-restic run holds $LOCK" >&2; exit 75; fi
  export CTG_RESTIC_LOCKED=1 CTG_RESTIC_LOCK_PID=$$
  wait_legacy || exit 75
fi
case "$cmd" in
  backup)
    if [ -x "$CONF/pre.sh" ]; then "$CONF/pre.sh" || { echo "pre.sh failed" >&2; exit 1; }; fi
    args=(backup --retry-lock "$RETRY_LOCK" --tag ctg-daily --exclude-caches --one-file-system=false)
    [ -f "$CONF/excludes" ] && args+=(--exclude-file "$CONF/excludes")
    [ -n "${CTG_LIMIT_UPLOAD:-}" ] && args+=(--limit-upload "$CTG_LIMIT_UPLOAD")   # KiB/s, optional (set in env)
    args+=(--files-from "$CONF/paths")
    restic "${args[@]}" "$@"; rc=$?
    # rc 3 = some source files unreadable (vanished while running): snapshot still written
    if [ $rc -eq 0 ] || [ $rc -eq 3 ]; then now > "$STATE/last-backup-ok"; rc=0; fi
    [ -x "$CONF/post.sh" ] && "$CONF/post.sh"
    exit $rc ;;
  prune)
    # A crashed/killed restic (e.g. an interrupted cutover job) leaves its lock behind and every later prune then
    # waits $RETRY_LOCK and fails (ollivanders 2026-11-08: lock from 2026-11-07 13:07, exit 11).
    # On exit 11 "already locked by PID <n> on <host>": if the lock is ours (same host) and PID <n> is no longer a
    # running restic, `restic unlock` (stale locks only, never --remove-all) and retry ONCE. A lock from another
    # host, or from a live PID, is never touched.
    out=$(mktemp); trap 'rm -f "$out"' EXIT
    restic forget --retry-lock "$RETRY_LOCK" --group-by host --keep-within "$KEEP" --prune "$@" 2> >(tee "$out" >&2); rc=$?
    if [ $rc -eq 11 ]; then
      lpid=$(sed -n 's/.*already locked by PID \([0-9][0-9]*\) on \(.*\) by .*/\1/p' "$out" | head -1)
      lhost=$(sed -n 's/.*already locked by PID \([0-9][0-9]*\) on \(.*\) by .*/\2/p' "$out" | head -1)
      if [ -n "$lpid" ] && [ "$lhost" = "$(hostname)" ] && ! { [ -r "/proc/$lpid/comm" ] && grep -q '^restic$' "/proc/$lpid/comm"; }; then
        echo "ctg-restic: lock held by dead PID $lpid on this host ($lhost): removing stale locks and retrying once" >&2
        restic unlock && restic forget --retry-lock "$RETRY_LOCK" --group-by host --keep-within "$KEEP" --prune "$@"; rc=$?
      else
        echo "ctg-restic: repo locked by PID ${lpid:-?} on ${lhost:-?}: not stale (live PID or another host), leaving it" >&2
      fi
    fi
    [ $rc -eq 0 ] && now > "$STATE/last-prune-ok"
    exit $rc ;;
  check)
    if restic check --retry-lock "$RETRY_LOCK" --read-data-subset=5% "$@"; then now > "$STATE/last-check-ok"; rm -f "$STATE/last-check-fail"; else now > "$STATE/last-check-fail"; exit 1; fi ;;
  *) exec restic "$cmd" "$@" ;;
esac
