#!/usr/bin/env bash
set -euo pipefail

PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BACKUP_DIR="${BACKUP_DIR:-/data/davos-backups}"
CRON_TIME="${CRON_TIME:-30 2 * * *}"
KEEP_DAYS="${KEEP_DAYS:-14}"
COMPOSE_FILE="${COMPOSE_FILE:-$PROJECT_DIR/docker-compose.yml}"
CRON_LINE="$CRON_TIME cd \"$PROJECT_DIR\" && BACKUP_DIR=\"$BACKUP_DIR\" KEEP_DAYS=\"$KEEP_DAYS\" COMPOSE_FILE=\"$COMPOSE_FILE\" ./scripts/backup-db.sh >> \"$BACKUP_DIR/backup.log\" 2>&1"

mkdir -p "$BACKUP_DIR"
(crontab -l 2>/dev/null | grep -v "backup-db.sh" || true; echo "$CRON_LINE") | crontab -
echo "已安装数据库定时备份："
echo "$CRON_LINE"
echo "备份目录：$BACKUP_DIR"
echo "保留天数：$KEEP_DAYS"
