#!/usr/bin/env bash
# 每日 sqlite → aliyun OSS 备份（跑在 epsilon 上，crontab 触发）。
# 要求：/usr/local/bin/aliyun 已配置（profile 名 xiangqin，aliyun/main 凭证）。

set -euo pipefail

DB_PATH="${DB_PATH:-/opt/xiangqin/data/xiangqin.db}"
BUCKET="${BUCKET:-agentaily-backup-xiangqin-prod}"
ENDPOINT="oss-cn-hangzhou.aliyuncs.com"
DATE=$(date +%Y%m%d)
TMP_DIR=$(mktemp -d)
trap 'rm -rf "$TMP_DIR"' EXIT

BACKUP_FILE="${TMP_DIR}/xiangqin-${DATE}.db"
GZIP_FILE="${BACKUP_FILE}.gz"

echo "[1/3] sqlite 原子快照"
sqlite3 "$DB_PATH" ".backup '${BACKUP_FILE}'"
gzip "$BACKUP_FILE"

echo "[2/3] 上传到 OSS"
aliyun --profile xiangqin oss cp "$GZIP_FILE" \
    "oss://${BUCKET}/daily/xiangqin-${DATE}.db.gz" \
    -e "$ENDPOINT"

echo "[3/3] 删 30 天前的备份"
CUTOFF=$(date -d '30 days ago' +%Y%m%d 2>/dev/null || date -v-30d +%Y%m%d)
aliyun --profile xiangqin oss ls "oss://${BUCKET}/daily/" -e "$ENDPOINT" | \
    awk '{print $NF}' | grep -E 'xiangqin-[0-9]{8}\.db\.gz$' | while read -r key; do
    fdate=$(echo "$key" | grep -oE '[0-9]{8}')
    if [[ "$fdate" < "$CUTOFF" ]]; then
        aliyun --profile xiangqin oss rm "$key" -e "$ENDPOINT" -f
    fi
done

echo "done: oss://${BUCKET}/daily/xiangqin-${DATE}.db.gz"
