#!/usr/bin/env bash
# 从 OSS 取最新备份，解压到 /opt/xiangqin/data/restore-<ts>/xiangqin.db。
# 默认不覆盖 prod 数据库（需要手动 rename + systemctl restart）。
#
# 用法:
#   scripts/restore.sh                 # 取最新 daily 备份
#   scripts/restore.sh 20260422        # 取指定日期的备份
#   scripts/restore.sh --in-place      # 覆盖 prod（谨慎！先 stop 服务）

set -euo pipefail

BUCKET="${BUCKET:-agentaily-backup-xiangqin-prod}"
ENDPOINT="oss-cn-hangzhou.aliyuncs.com"
DATA_DIR="/opt/xiangqin/data"

DATE_ARG=""
IN_PLACE=0
for arg in "$@"; do
    case "$arg" in
        --in-place) IN_PLACE=1 ;;
        [0-9]*) DATE_ARG="$arg" ;;
    esac
done

if [[ -z "$DATE_ARG" ]]; then
    # 取列表里最新那条
    DATE_ARG=$(aliyun --profile xiangqin oss ls "oss://${BUCKET}/daily/" -e "$ENDPOINT" \
        | awk '{print $NF}' \
        | grep -oE 'xiangqin-[0-9]{8}\.db\.gz$' \
        | grep -oE '[0-9]{8}' \
        | sort | tail -1)
    if [[ -z "$DATE_ARG" ]]; then
        echo "no backups found in oss://${BUCKET}/daily/" >&2
        exit 1
    fi
fi

KEY="daily/xiangqin-${DATE_ARG}.db.gz"
echo "[1/3] 下载 oss://${BUCKET}/${KEY}"

TS=$(date +%Y%m%d%H%M%S)
RESTORE_DIR="${DATA_DIR}/restore-${TS}"
mkdir -p "$RESTORE_DIR"

TMP_GZ="${RESTORE_DIR}/xiangqin.db.gz"
aliyun --profile xiangqin oss cp "oss://${BUCKET}/${KEY}" "$TMP_GZ" -e "$ENDPOINT" --force

echo "[2/3] 解压"
gunzip "$TMP_GZ"  # → $RESTORE_DIR/xiangqin.db
RESTORED="${RESTORE_DIR}/xiangqin.db"

echo "[3/3] 完整性校验"
sqlite3 "$RESTORED" 'PRAGMA integrity_check' | head -1
sqlite3 "$RESTORED" 'SELECT COUNT(*) AS users FROM users'
sqlite3 "$RESTORED" 'SELECT COUNT(*) AS orders FROM exposure_orders'

echo
echo "恢复到 $RESTORED"
if [[ "$IN_PLACE" -eq 1 ]]; then
    echo
    echo "[IN-PLACE] 停服务 + 覆盖 prod + 重启"
    systemctl stop xiangqin
    mv "${DATA_DIR}/xiangqin.db" "${DATA_DIR}/xiangqin.db.before-restore-${TS}" 2>/dev/null || true
    cp "$RESTORED" "${DATA_DIR}/xiangqin.db"
    chmod 600 "${DATA_DIR}/xiangqin.db"
    systemctl start xiangqin
    echo "done, 原库备份到 xiangqin.db.before-restore-${TS}"
else
    echo "（未 --in-place，prod 未动；手动覆盖时先 systemctl stop xiangqin）"
fi
