#!/usr/bin/env bash
# entrypoint.sh —— 启动备份容器，初始化环境，拉起 crond
set -euo pipefail

LOG_FILE=/var/log/backup/cron.log

# ---------- 检查必要变量 ----------
required_vars="BACKUP_S3_BUCKET BACKUP_S3_PREFIX AGE_PUBLIC_KEY
               BACKUP_AWS_ACCESS_KEY_ID BACKUP_AWS_SECRET_ACCESS_KEY"
for v in $required_vars; do
    if [ -z "${!v:-}" ]; then
        echo "[ERROR] 缺少必要环境变量: ${v}" >&2
        exit 1
    fi
done

# ---------- 配置 AWS 凭据（备份专用 IAM 账号） ----------
mkdir -p /root/.aws
cat > /root/.aws/credentials << AWSEOF
[backup]
aws_access_key_id = ${BACKUP_AWS_ACCESS_KEY_ID}
aws_secret_access_key = ${BACKUP_AWS_SECRET_ACCESS_KEY}
AWSEOF

cat > /root/.aws/config << AWSEOF
[profile backup]
region = ${BACKUP_AWS_REGION:-ap-southeast-1}
output = json
AWSEOF

chmod 600 /root/.aws/credentials /root/.aws/config

# ---------- 写入 age 公钥 ----------
echo "${AGE_PUBLIC_KEY}" > /etc/age-public.txt
chmod 644 /etc/age-public.txt

# ---------- 写入 age 私钥（仅 DR 演练时需要） ----------
if [ -n "${AGE_PRIVATE_KEY:-}" ]; then
    echo "${AGE_PRIVATE_KEY}" > /etc/age-private.txt
    chmod 600 /etc/age-private.txt
fi

# ---------- 把所有环境变量写入 /etc/backup-env.sh，供 cron job 使用 ----------
# （cron 不继承环境变量）
{
    echo "# 自动生成，cron job 使用"
    for v in BACKUP_S3_BUCKET BACKUP_S3_PREFIX BACKUP_AWS_REGION \
              BACKUP_AWS_ACCESS_KEY_ID BACKUP_AWS_SECRET_ACCESS_KEY \
              MYSQL_HOST MYSQL_PORT MYSQL_USER MYSQL_PASSWORD MYSQL_DATABASES \
              MYSQL_DATADIR \
              PG_HOST PG_PORT PG_USER PG_PASSWORD PG_DATABASES \
              MARZBAN_DB_PATH \
              BACKUP_DIR \
              NOTIFY_WEBHOOK_URL; do
        val="${!v:-}"
        if [ -n "${val}" ]; then
            printf 'export %s=%q\n' "${v}" "${val}"
        fi
    done
    echo 'export AWS_PROFILE=backup'
    echo 'export AWS_CONFIG_FILE=/root/.aws/config'
    echo 'export AWS_SHARED_CREDENTIALS_FILE=/root/.aws/credentials'
} > /etc/backup-env.sh
chmod 600 /etc/backup-env.sh

# ---------- 设置本地备份目录 ----------
BACKUP_DIR="${BACKUP_DIR:-/backup}"
mkdir -p \
    "${BACKUP_DIR}/mysql/full" \
    "${BACKUP_DIR}/mysql/inc" \
    "${BACKUP_DIR}/mysql/binlog" \
    "${BACKUP_DIR}/postgres" \
    "${BACKUP_DIR}/marzban" \
    "${BACKUP_DIR}/encrypt"

echo "[INFO] 备份容器启动成功，等待 cron 任务..."
echo "[INFO] S3 目标: s3://${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}"
echo "[INFO] 备份目录: ${BACKUP_DIR}"

# ---------- 启动 cron 并保持前台 ----------
# 执行一次启动验证
/scripts/verify-rpo-rto.sh --status-only 2>&1 | head -5 || true

# 启动 cron daemon（后台，Ubuntu 的 cron 默认 daemon 模式）
cron

# exec tail 成为主进程，接收 Docker stop 信号，并实时输出日志到 stdout
exec tail -F "${LOG_FILE}"
