"""Create a consistent backup ZIP of the data directory (SQLite + uploads + storage). Usage: backup_data.py Prints the created zip path on stdout. Exit codes: 0 ok, 1 error, 2 bad args. """ import shutil import sqlite3 import sys import tempfile import time import zipfile from pathlib import Path def main() -> int: if len(sys.argv) != 3: print("usage: backup_data.py ", file=sys.stderr) return 2 data = Path(sys.argv[1]) backups = Path(sys.argv[2]) backups.mkdir(parents=True, exist_ok=True) stamp = time.strftime("%Y%m%d-%H%M%S") out_zip = backups / f"backup-{stamp}.zip" stage = Path(tempfile.mkdtemp(prefix="wvt-bk-", dir=str(backups))) try: db = data / "work_tracker.db" if db.is_file(): src = sqlite3.connect(db) dst = sqlite3.connect(stage / "work_tracker.db") try: with dst: src.backup(dst) finally: dst.close() src.close() for sub in ("uploads", "storage"): s = data / sub if s.is_dir(): shutil.copytree(s, stage / sub, dirs_exist_ok=True) with zipfile.ZipFile(out_zip, "w", compression=zipfile.ZIP_DEFLATED) as zf: for path in sorted(stage.rglob("*")): if path.is_file(): zf.write(path, path.relative_to(stage).as_posix()) print(out_zip) return 0 except Exception as exc: print(f"ERROR {type(exc).__name__}: {exc}", file=sys.stderr) return 1 finally: shutil.rmtree(stage, ignore_errors=True) if __name__ == "__main__": raise SystemExit(main())