#!/usr/bin/env python3
"""
alfred-zfs-snap-prune — Sovereign OpenZFS Automatic Pre-OTA & APT Snapshot Retention
Keeps the newest N (default: 2) automatic `pre-ota-*` / `pre-panel-ota-*` snapshots
and newest M (default: 1) `apt-pre-*` / `apt-snap-*` snapshots on `rpool/ROOT/*`,
plus trims `/var/backups/alfred-dc-ota/*.tar.gz` to the newest N archives.
Never touches manual, user, or domain snapshots, and never touches non-rpool disks.
"""
import argparse
import glob
import os
import re
import shutil
import subprocess

AUTO_SNAP_RE = re.compile(r"^rpool/ROOT/[^@]+@(?:pre-(?:panel-)?ota-|apt-(?:pre|snap)-)")


def list_rpool_snapshots() -> list[str]:
    if not shutil.which("zfs"):
        return []
    r = subprocess.run(
        ["zfs", "list", "-H", "-t", "snapshot", "-o", "name", "-s", "creation", "-r", "rpool/ROOT"],
        stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=15
    )
    if r.returncode != 0:
        return []
    return [ln.strip() for ln in r.stdout.splitlines() if ln.strip()]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--keep", type=int, default=2)
    ap.add_argument("--dry-run", action="store_true")
    args = ap.parse_args()

    snaps = list_rpool_snapshots()
    auto_snaps = [s for s in snaps if AUTO_SNAP_RE.match(s)]

    # On panel-only servers that have pre-panel-ota-* snapshots, drop any stray aborted v7.5.* ws snapshot
    has_panel_ota = any("@pre-panel-ota-" in s for s in auto_snaps)
    to_destroy = []
    if has_panel_ota:
        clean_auto = []
        for s in auto_snaps:
            if "-to-v7.5." in s:
                to_destroy.append(s)
            else:
                clean_auto.append(s)
        auto_snaps = clean_auto

    if len(auto_snaps) > args.keep:
        to_destroy.extend(auto_snaps[: len(auto_snaps) - args.keep])

    destroyed = 0
    for s in to_destroy:
        if args.dry_run:
            print(f"[dry-run] would destroy {s}")
        else:
            rc = subprocess.call(["zfs", "destroy", s])
            if rc == 0:
                destroyed += 1
                print(f"[alfred-zfs-snap-prune] destroyed {s}")

    # Trim /var/backups/alfred-dc-ota/*.tar.gz to newest keep
    bdir = "/var/backups/alfred-dc-ota"
    if os.path.isdir(bdir):
        tars = sorted(glob.glob(os.path.join(bdir, "pre-*ota-*.tar.gz")), key=os.path.getmtime)
        if len(tars) > args.keep:
            for old_t in tars[: len(tars) - args.keep]:
                if not args.dry_run:
                    try:
                        os.unlink(old_t)
                    except OSError:
                        pass

    print(f"[alfred-zfs-snap-prune] complete (destroyed={destroyed}, kept={min(len(auto_snaps), args.keep)})")


if __name__ == "__main__":
    main()
