#!/usr/bin/python3
"""ctg-restic pre-hook (linked as /etc/ctg-backup/pre.sh): consistent copy of the live SQLite DB (WAL-safe, one backup() step)
into /var/backups/yes-site, which /etc/ctg-backup/paths then backs up to B2 (encrypted restic, 30-day retention).
When YES_DB_URL (postgres://...) is configured the data lives in the shared PostgreSQL cluster, which pgBackRest already backs up
(30-day retention): no SQLite snapshot is taken and a stale one is removed; restic keeps only /etc/yes-site and the thumbnails."""
import os, re, sqlite3, sys
def configured(name):
    if os.environ.get(name):
        return True
    for f in ("/etc/yes-site/yes-site.env", "/etc/yes-site/secrets.env"):
        try:
            if re.search(r"^\s*" + name + r"=\S", open(f).read(), re.M):
                return True
        except OSError:
            pass
    return False
SRC = os.environ.get("YES_DB", "/var/lib/yes-site/yes.db")
DIR = "/var/backups/yes-site"
if configured("YES_DB_URL"):
    for n in ("yes.db", "yes.db.tmp"):
        try:
            os.remove(os.path.join(DIR, n))
        except OSError:
            pass
    sys.exit(0)
os.makedirs(DIR, mode=0o700, exist_ok=True)
tmp = os.path.join(DIR, "yes.db.tmp")
if os.path.exists(tmp):
    os.remove(tmp)
src = sqlite3.connect(SRC)
dst = sqlite3.connect(tmp)
src.backup(dst)
ok = dst.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
dst.close(); src.close()
if not ok:
    sys.exit("integrity_check failed on the snapshot")
os.chmod(tmp, 0o600)
os.replace(tmp, os.path.join(DIR, "yes.db"))
