#!/usr/bin/env bash
# Install daily backup cron: Beijing 00:00 (CRON_TZ=Asia/Shanghai).
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
BACKUP_SCRIPT="$SCRIPT_DIR/backup_data.sh"
INSTANCE_NAME="${BACKUP_INSTANCE:-$(basename "$PROJECT_DIR")}"
LOG_FILE="${BACKUP_CRON_LOG:-/var/log/crypto-monitor-backup-${INSTANCE_NAME}.log}"

if [[ ! -x "$BACKUP_SCRIPT" ]]; then
  chmod +x "$BACKUP_SCRIPT"
fi

TMP="$(mktemp)"
trap 'rm -f "$TMP"' EXIT

{
  crontab -l 2>/dev/null | grep -vF "$BACKUP_SCRIPT" || true
  echo "CRON_TZ=Asia/Shanghai"
  echo "0 0 * * * $BACKUP_SCRIPT >> $LOG_FILE 2>&1"
} >"$TMP"

awk '
  BEGIN { tz = 0 }
  /^CRON_TZ=Asia\/Shanghai$/ {
    if (tz++) next
  }
  { print }
' "$TMP" >"${TMP}.2"
mv "${TMP}.2" "$TMP"

crontab "$TMP"
echo "Installed cron for $INSTANCE_NAME"
echo "  Schedule : daily 00:00 Asia/Shanghai"
echo "  Script   : $BACKUP_SCRIPT"
echo "  Log      : $LOG_FILE"
crontab -l | grep -F "$BACKUP_SCRIPT" || true
