#!/bin/bash
# MySQL 备份 cron 调度入口
# 调用 backup-mysql.sh 备份所有微服务数据库，单个失败不阻塞其他
# 用法: backup-cron.sh [--keep <days>]
set -euo pipefail

# ---------- 参数解析 ----------
KEEP_DAYS=7

while [[ $# -gt 0 ]]; do
  case "$1" in
    --keep)
      KEEP_DAYS="${2:-7}"
      shift 2
      ;;
    -h|--help)
      echo "Usage: $0 [--keep <days>]" >&2
      echo "  --keep  保留天数（默认 7）" >&2
      exit 0
      ;;
    *)
      echo "[ERROR] 未知参数: $1" >&2
      exit 1
      ;;
  esac
done

# ---------- 配置 ----------
# 每个服务对应一个独立数据库
SERVICES=(iam core-edu content msg classes)

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKUP_SCRIPT="${SCRIPT_DIR}/backup-mysql.sh"

# ---------- 日志函数 ----------
log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >&2
}

if [[ ! -x "$BACKUP_SCRIPT" ]]; then
  log "[ERROR] 备份脚本不存在或不可执行: ${BACKUP_SCRIPT}"
  exit 1
fi

# ---------- 主流程 ----------
log "[INFO] 开始批量备份，共 ${#SERVICES[@]} 个服务"

TOTAL=0
SUCCESS=0
FAILED=0
FAILED_LIST=()

for svc in "${SERVICES[@]}"; do
  TOTAL=$((TOTAL + 1))
  log "[INFO] ---- 备份服务: ${svc} ----"
  if "$BACKUP_SCRIPT" --service "$svc" --keep "$KEEP_DAYS"; then
    SUCCESS=$((SUCCESS + 1))
    log "[INFO] 服务 ${svc} 备份成功"
  else
    FAILED=$((FAILED + 1))
    FAILED_LIST+=("$svc")
    log "[ERROR] 服务 ${svc} 备份失败，继续下一个"
  fi
done

# ---------- 汇总 ----------
log "[INFO] 批量备份结束: 总计=${TOTAL} 成功=${SUCCESS} 失败=${FAILED}"

if [[ ${FAILED} -gt 0 ]]; then
  log "[ERROR] 失败服务列表: ${FAILED_LIST[*]}"
  exit 1
fi

exit 0
