#!/bin/bash
# ═══════════════════════════════════════════════════════════
# 光湖智库数据备份脚本 · 定时备份到腾讯云COS
# ═══════════════════════════════════════════════════════════
#
# 项目编号: ZY-PROJ-006
# 服务器:   ZY-SVR-006 (43.153.203.105 · 新加坡)
# 守护:     铸渊 · ICE-GL-ZY001
# 版权:     国作登字-2026-A-00037559
#
# 功能:
#   1. 备份 /opt/zhiku/data 目录到腾讯云 COS
#   2. 每周一全量备份，其他日增量备份
#   3. 保留最近7天的备份
#   4. 日志记录每次备份操作
#
# 运行时间: 每日 04:00 (UTC+8)
# ═══════════════════════════════════════════════════════════

set -euo pipefail

# ─── 配置变量 ───
BACKUP_SOURCE="/opt/zhiku/data"
BACKUP_DEST="cos://$ZY_COS_BUCKET/backups/zhiku-data"
LOG_FILE="/var/log/zhiku/backup.log"
TEMP_DIR="/tmp/zhiku-backup"

# ─── 确保目录存在 ───
mkdir -p "$TEMP_DIR"
mkdir -p "$(dirname "$LOG_FILE")"

echo "[$(date '+%Y-%m-%d %H:%M:%S')] 开始备份 $BACKUP_SOURCE 到 $BACKUP_DEST" >> "$LOG_FILE"

# ─── 判断备份类型 ───
DAY_OF_WEEK=$(date +%u)
BACKUP_TYPE="incremental"
BACKUP_SUFFIX="inc"

if [ "$DAY_OF_WEEK" -eq 1 ]; then
  BACKUP_TYPE="full"
  BACKUP_SUFFIX="full"
fi

# ─── 创建备份文件 ───
TIMESTAMP=$(date '+%Y%m%d-%H%M%S')
BACKUP_FILE="zhiku-data-$TIMESTAMP-$BACKUP_SUFFIX.tar.gz"
BACKUP_PATH="$TEMP_DIR/$BACKUP_FILE"

# 全量备份直接打包
if [ "$BACKUP_TYPE" = "full" ]; then
  tar -czf "$BACKUP_PATH" -C "$BACKUP_SOURCE" .
else
  # 增量备份基于前一天的全量或增量
  LAST_BACKUP=$(find "$TEMP_DIR" -name "zhiku-data-*-*.tar.gz" | sort | tail -n 1)
  
  if [ -z "$LAST_BACKUP" ]; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] 警告: 找不到之前的备份，执行全量备份" >> "$LOG_FILE"
    tar -czf "$BACKUP_PATH" -C "$BACKUP_SOURCE" .
  else
    # 使用--newer-mtime参数只备份修改过的文件
    tar -czf "$BACKUP_PATH" -C "$BACKUP_SOURCE" --newer-mtime="$(date -d @$(stat -c %Y "$LAST_BACKUP") '+%Y-%m-%d %H:%M:%S')" .
  fi
fi

# ─── 上传到COS ───
coscli cp "$BACKUP_PATH" "$BACKUP_DEST/$BACKUP_FILE" >> "$LOG_FILE" 2>&1

# ─── 清理旧备份 ───
find "$TEMP_DIR" -name "zhiku-data-*.tar.gz" -mtime +7 -delete

# ─── 记录完成 ───
BACKUP_SIZE=$(du -h "$BACKUP_PATH" | cut -f1)
echo "[$(date '+%Y-%m-%d %H:%M:%S')] 备份完成: $BACKUP_FILE ($BACKUP_SIZE)" >> "$LOG_FILE"

# ─── 返回状态 ───
exit 0