#!/bin/bash
set -euo pipefail
umask 0077

backup_root=/var/backups/wechat-formatter/daily
mkdir -p "$backup_root"
chmod 0700 "$backup_root"
exec 9>"$backup_root/.lock"
flock -n 9 || exit 0

backup_stamp=$(date -u +%Y%m%dT%H%M%SZ)
backup_stage=$(mktemp -d "$backup_root/.pending.XXXXXXXX")
trap 'rm -rf -- "$backup_stage"' EXIT

# pg_dump takes a consistent database snapshot without stopping PostgreSQL.
docker exec wechat-postgres sh -c 'exec pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" --format=custom' > "$backup_stage/database.dump"
docker exec -i wechat-postgres pg_restore --list < "$backup_stage/database.dump" > "$backup_stage/database.contents"
# Assets are immutable; archive them after the DB snapshot to include referenced files.
tar -czf "$backup_stage/assets.tar.gz" -C /var/lib/wechat-formatter assets
tar -czf "$backup_stage/config.tar.gz" -C / \
  etc/wechat-formatter \
  etc/systemd/system/wechat-formatter.service \
  etc/systemd/system/wechat-formatter-worker.service \
  etc/systemd/system/wechat-formatter-backup.service \
  etc/systemd/system/wechat-formatter-backup.timer \
  etc/nginx/sites-available/wechat-formatter
tar -tzf "$backup_stage/assets.tar.gz" > /dev/null
tar -tzf "$backup_stage/config.tar.gz" > /dev/null
(cd "$backup_stage" && sha256sum database.dump database.contents assets.tar.gz config.tar.gz > SHA256SUMS)
mv "$backup_stage" "$backup_root/$backup_stamp"
trap - EXIT

# Retention only applies to this script's completed daily snapshots.
find "$backup_root" -mindepth 1 -maxdepth 1 -type d -name '20??????T??????Z' -mtime +14 -exec rm -rf -- {} +
echo "WeChat Formatter backup complete: $backup_root/$backup_stamp"
