#!/usr/bin/env bash
# Nexus — 安装/更新 host crontab：health_monitor + db_backup
#
#   sudo bash deploy/install_ops_cron.sh
#   NEXUS_ROOT=/opt/nexus sudo bash deploy/install_ops_cron.sh
set -euo pipefail

NEXUS_ROOT="${NEXUS_ROOT:-/opt/nexus}"
DEPLOY_DIR="${NEXUS_ROOT}/deploy"
HEALTH_MARKER="nexus-health-monitor"
BACKUP_MARKER="nexus-mysql-backup"
HEALTH_LOG="${NEXUS_HEALTH_LOG:-/var/log/nexus_health.log}"
BACKUP_LOG="${NEXUS_BACKUP_LOG:-/var/log/nexus_backup.log}"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

info() { echo -e "${GREEN}[INFO]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }

if [[ "$(id -u)" -ne 0 ]]; then
    error "请使用 root 运行: sudo bash $0"
    exit 1
fi

ensure_crontab() {
    if command -v crontab >/dev/null 2>&1; then
        return 0
    fi
    warn "未检测到 crontab，尝试安装 cron 包…"
    if command -v apt-get >/dev/null 2>&1; then
        export DEBIAN_FRONTEND=noninteractive
        apt-get update -qq
        apt-get install -y -qq cron
        systemctl enable --now cron 2>/dev/null || systemctl enable --now crond 2>/dev/null || true
    elif command -v yum >/dev/null 2>&1; then
        yum install -y cronie
        systemctl enable --now crond 2>/dev/null || true
    fi
    if ! command -v crontab >/dev/null 2>&1; then
        error "无法安装 crontab（请手动: apt install cron）"
        exit 1
    fi
    info "cron 已安装"
}

ensure_crontab

for f in \
    "${DEPLOY_DIR}/health_monitor.sh" \
    "${DEPLOY_DIR}/db_backup.sh" \
    "${DEPLOY_DIR}/mysql_dump_to_file.sh" \
    ; do
    if [[ ! -f "$f" ]]; then
        error "缺少脚本: $f"
        exit 1
    fi
    chmod +x "$f" 2>/dev/null || true
done

touch "$HEALTH_LOG" "$BACKUP_LOG" 2>/dev/null || true
chmod 644 "$HEALTH_LOG" "$BACKUP_LOG" 2>/dev/null || true

HEALTH_LINE="* * * * * NEXUS_DEPLOY_DIR=${NEXUS_ROOT} bash ${DEPLOY_DIR}/health_monitor.sh >> ${HEALTH_LOG} 2>&1 # ${HEALTH_MARKER}"
BACKUP_LINE="0 3 * * * NEXUS_ROOT=${NEXUS_ROOT} bash ${DEPLOY_DIR}/db_backup.sh >> ${BACKUP_LOG} 2>&1 # ${BACKUP_MARKER}"

existing="$(crontab -l 2>/dev/null || true)"
filtered="$(printf '%s\n' "$existing" | grep -v "$HEALTH_MARKER" | grep -v "$BACKUP_MARKER" | grep -v 'deploy/health_monitor.sh' | grep -v 'deploy/db_backup.sh' || true)"
{
    printf '%s\n' "$filtered" | sed '/^[[:space:]]*$/d'
    echo "$HEALTH_LINE"
    echo "$BACKUP_LINE"
} | crontab -

info "已写入 crontab:"
crontab -l | grep -E "$HEALTH_MARKER|$BACKUP_MARKER" || true
info "健康巡检日志: $HEALTH_LOG"
info "MySQL 备份日志: $BACKUP_LOG"
