#!/usr/bin/env bash
# 数据库分库备份脚本
# 用法：backup.sh [assets|metrics|all]
#   assets  -> 备份 assets.db，保留 14 份（建议每日）
#   metrics -> 备份 metrics.db，保留 4 份（建议每周）
#   all     -> 两者都备份
set -euo pipefail

APP_DIR="${APP_DIR:-/opt/vps-manager}"
cd "$APP_DIR"

TARGET="${1:-all}"

python3 - "$TARGET" <<'PYEOF'
import sqlite3
import sys
from datetime import datetime
from pathlib import Path

target = sys.argv[1]
data_dir = Path("data")
backup_root = data_dir / "backups"
ts = datetime.now().strftime("%Y%m%d_%H%M%S")


def backup(db_name: str, keep: int) -> None:
    src = data_dir / db_name
    stem = db_name.replace(".db", "")
    if not src.exists():
        print(f"[skip] {db_name} 不存在")
        return
    out_dir = backup_root / stem
    out_dir.mkdir(parents=True, exist_ok=True)
    dst = out_dir / f"{stem}_{ts}.db"

    con = sqlite3.connect(str(src))
    bkp = sqlite3.connect(str(dst))
    con.backup(bkp)
    bkp.close()
    con.close()

    files = sorted(
        out_dir.glob(f"{stem}_*.db"),
        key=lambda p: p.stat().st_mtime,
        reverse=True,
    )
    for old in files[keep:]:
        old.unlink()
    print(f"[ok] {db_name} -> {dst}（保留 {keep} 份）")


if target in ("assets", "all"):
    backup("assets.db", 14)
if target in ("metrics", "all"):
    backup("metrics.db", 4)
PYEOF
