#!/usr/bin/env bash
# snap — backup / snapshot tooling (feature T11)
# Filesystem snapshots + rsync jobs, restore-first.
#
# Usage:
#   snap rsync SOURCE DEST [--name NAME] [--exclude PAT]... [--delete] [--dry-run]
#   snap list DEST
#   snap restore SNAPSHOT DEST [--force]
#   snap btrfs SUBVOL DEST [--readonly]
#   snap --help
#
# rsync mode: timestamped snapshots under DEST (e.g. 20261008T120000Z/),
# hardlink-dedup'd against the previous snapshot (--link-dest), with a
# `latest` symlink updated after a successful run.
#
# restore is RESTORE-FIRST: it never overwrites an existing non-empty DEST
# unless you pass --force.
set -uo pipefail

usage() { awk 'NR>1 && /^#/{sub(/^# ?/,""); print} NR>1 && !/^#/ && NF{exit}' "$0"; }

ts() { date -u +%Y%m%dT%H%M%S.%3NZ; }

rsync_snap() {
    local src="" dest="" name="" delete=0 dryrun=0
    local excludes=()
    while [ $# -gt 0 ]; do
        case "$1" in
            --name)    name="$2"; shift 2 ;;
            --exclude) excludes+=("$2"); shift 2 ;;
            --delete)  delete=1; shift ;;
            --dry-run) dryrun=1; shift ;;
            --help|-h) usage; exit 0 ;;
            -*) echo "snap: unknown option: $1" >&2; usage; exit 2 ;;
            *) if [ -z "$src" ]; then src="$1"; elif [ -z "$dest" ]; then dest="$1"; else echo "snap: too many args: $1" >&2; exit 2; fi; shift ;;
        esac
    done
    [ -n "$src" ] && [ -n "$dest" ] || { echo "snap: SOURCE and DEST are required" >&2; usage; exit 2; }
    [ -e "$src" ] || { echo "snap: SOURCE does not exist: $src" >&2; exit 1; }
    mkdir -p "$dest"

    local stamp; stamp="$(ts)"
    [ -n "$name" ] && stamp="${stamp}-${name}"
    local base="$stamp" n=1 snapdir="$dest/$stamp"
    while [ -e "$snapdir" ]; do n=$((n+1)); stamp="${base}-${n}"; snapdir="$dest/$stamp"; done
    local prev; prev="$(readlink -f "$dest/latest" 2>/dev/null || true)"

    local rsargs=( -a --numeric-ids )
    [ -n "$prev" ] && [ -d "$prev" ] && rsargs+=( --link-dest="$prev" )
    for e in "${excludes[@]}"; do rsargs+=( --exclude="$e" ); done
    [ "$delete" -eq 1 ] && rsargs+=( --delete )

    local srcref="$src"
    [ -d "$src" ] && srcref="$src/"

    echo "snap: rsync $srcref -> $snapdir"
    echo "  (link-dest: ${prev:-<none>}, excludes: ${#excludes[@]}, delete: $delete)"
    if [ "$dryrun" -eq 1 ]; then
        rsync "${rsargs[@]}" --dry-run "$srcref" "$snapdir/"
        echo "snap: dry-run complete (nothing written)"
        return 0
    fi

    rsync "${rsargs[@]}" "$srcref" "$snapdir/"
    ln -sfn "$(basename "$snapdir")" "$dest/latest"
    echo "snap: done -> $snapdir (latest -> $(basename "$snapdir"))"
}

list_snaps() {
    local dest="${1:-}"
    [ -n "$dest" ] || { echo "snap: DEST is required" >&2; usage; exit 2; }
    [ -d "$dest" ] || { echo "snap: no such snapshot dir: $dest" >&2; exit 1; }
    local d
    for d in "$dest"/*/; do
        [ -d "$d" ] || continue
        local n; n="$(basename "$d")"
        [ "$n" = "latest" ] && continue
        local size; size="$(du -sh "$d" 2>/dev/null | cut -f1)"
        local cnt; cnt="$(find "$d" -type f 2>/dev/null | wc -l)"
        printf '%-32s %8s %8s files\n' "$n" "$size" "$cnt"
    done
    echo "latest -> $(readlink "$dest/latest" 2>/dev/null || echo none)"
}

restore_snap() {
    local snap="" dest="" force=0
    while [ $# -gt 0 ]; do
        case "$1" in
            --force) force=1; shift ;;
            --help|-h) usage; exit 0 ;;
            -*) echo "snap: unknown option: $1" >&2; usage; exit 2 ;;
            *) if [ -z "$snap" ]; then snap="$1"; elif [ -z "$dest" ]; then dest="$1"; else echo "snap: too many args: $1" >&2; exit 2; fi; shift ;;
        esac
    done
    [ -n "$snap" ] && [ -n "$dest" ] || { echo "snap: SNAPSHOT and DEST are required" >&2; usage; exit 2; }
    [ -d "$snap" ] || { echo "snap: not a directory: $snap" >&2; exit 1; }
    if [ -e "$dest" ] && [ -n "$(ls -A "$dest" 2>/dev/null)" ] && [ "$force" -ne 1 ]; then
        echo "snap: refusing to restore over non-empty '$dest' (restore-first)" >&2
        echo "  pass --force to rsync --delete into it, or choose an empty/new path." >&2
        exit 1
    fi
    mkdir -p "$dest"
    local rsargs=( -a --numeric-ids )
    [ "$force" -eq 1 ] && rsargs+=( --delete )
    rsync "${rsargs[@]}" "$snap/" "$dest/"
    echo "snap: restored $snap -> $dest"
}

btrfs_snap() {
    local subvol="" dest="" ro=0
    while [ $# -gt 0 ]; do
        case "$1" in
            --readonly|-r) ro=1; shift ;;
            --help|-h) usage; exit 0 ;;
            -*) echo "snap: unknown option: $1" >&2; usage; exit 2 ;;
            *) if [ -z "$subvol" ]; then subvol="$1"; elif [ -z "$dest" ]; then dest="$1"; else echo "snap: too many args: $1" >&2; exit 2; fi; shift ;;
        esac
    done
    [ -n "$subvol" ] && [ -n "$dest" ] || { echo "snap: SUBVOL and DEST are required" >&2; usage; exit 2; }
    local args=( subvolume snapshot )
    [ "$ro" -eq 1 ] && args+=( -r )
    args+=( "$subvol" "$dest" )
    if [ "$(id -u)" -eq 0 ]; then btrfs "${args[@]}";
    elif command -v sudo >/dev/null 2>&1; then sudo btrfs "${args[@]}";
    else btrfs "${args[@]}"; fi
}

case "${1:-}" in
    rsync)     shift; rsync_snap "$@" ;;
    list)      shift; list_snaps "$@" ;;
    restore)   shift; restore_snap "$@" ;;
    btrfs)     shift; btrfs_snap "$@" ;;
    --help|-h) usage ;;
    *) usage; exit 2 ;;
esac
