#!/usr/bin/env bash
set -euo pipefail
BACKUP_ROOT=${BACKUP_ROOT:-/var/backups/guanghu/forgejo}
RETENTION_DAYS=${RETENTION_DAYS:-14}
stamp=$(date -u +%Y%m%dT%H%M%SZ)
target="$BACKUP_ROOT/$stamp"
install -d -m 0700 "$target"
if [[ -f /var/lib/forgejo/data/forgejo.db ]]; then
  sqlite3 /var/lib/forgejo/data/forgejo.db ".backup '$target/forgejo.db'"
fi
tar -C / -czf "$target/forgejo-files.tgz" etc/forgejo var/lib/forgejo/data --exclude='var/lib/forgejo/data/forgejo.db'
sha256sum "$target"/* > "$target/SHA256SUMS"
find "$BACKUP_ROOT" -mindepth 1 -maxdepth 1 -type d -mtime "+$RETENTION_DAYS" -print -exec rm -rf -- {} +
printf 'FORGEJO_BACKUP_READY=%s\n' "$target"
