#!/usr/bin/env bash
# =============================================================================
#  SRP — Auto Cron Setup
#  Usage: bash setup-cron.sh [--php /usr/local/bin/php] [--dry-run]
#
#  Safe to run multiple times — skips jobs that already exist.
# =============================================================================

set -euo pipefail

# ── Defaults ──────────────────────────────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PHP_BIN=""
DRY_RUN=false

# ── Argument parsing ──────────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
    case "$1" in
        --php)    PHP_BIN="$2"; shift 2 ;;
        --dry-run) DRY_RUN=true; shift ;;
        *) echo "Unknown argument: $1"; exit 1 ;;
    esac
done

# ── Colors ────────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
CYAN='\033[0;36m'; BOLD='\033[1m'; RESET='\033[0m'

ok()   { echo -e "${GREEN}  ✔${RESET}  $*"; }
warn() { echo -e "${YELLOW}  ⚠${RESET}  $*"; }
info() { echo -e "${CYAN}  →${RESET}  $*"; }
err()  { echo -e "${RED}  ✖${RESET}  $*" >&2; }
head() { echo -e "\n${BOLD}$*${RESET}"; }

# ── Detect PHP binary ─────────────────────────────────────────────────────────
detect_php() {
    if [[ -n "$PHP_BIN" ]]; then
        if [[ ! -x "$PHP_BIN" ]]; then
            err "PHP binary tidak ditemukan: $PHP_BIN"
            exit 1
        fi
        echo "$PHP_BIN"
        return
    fi

    # Coba lokasi umum
    local candidates=(
        "$(which php 2>/dev/null || true)"
        /usr/local/bin/php
        /usr/bin/php
        /opt/cpanel/ea-php83/root/usr/bin/php
        /opt/cpanel/ea-php82/root/usr/bin/php
    )

    for bin in "${candidates[@]}"; do
        if [[ -n "$bin" && -x "$bin" ]]; then
            echo "$bin"
            return
        fi
    done

    err "PHP binary tidak ditemukan. Gunakan: bash setup-cron.sh --php /path/to/php"
    exit 1
}

# ── Add cron job (idempotent) ─────────────────────────────────────────────────
add_cron() {
    local schedule="$1"
    local command="$2"
    local label="$3"
    local log_file="$4"

    local full_cmd="${schedule} ${command} >> ${log_file} 2>&1"

    # Cek apakah command sudah ada di crontab
    if crontab -l 2>/dev/null | grep -qF "$command"; then
        warn "${label} — sudah ada, skip"
        return 0
    fi

    if [[ "$DRY_RUN" == true ]]; then
        info "[DRY-RUN] Akan ditambahkan: ${full_cmd}"
        return 0
    fi

    # Tambahkan ke crontab
    (crontab -l 2>/dev/null; echo "${full_cmd}") | crontab -
    ok "${label} — ditambahkan"
}

# =============================================================================
#  MAIN
# =============================================================================

head "SRP Cron Setup"
echo "  Base path : ${SCRIPT_DIR}"
echo ""

# ── Detect PHP ────────────────────────────────────────────────────────────────
head "Deteksi PHP"
PHP_BIN="$(detect_php)"
PHP_VER="$("$PHP_BIN" -r 'echo PHP_VERSION;' 2>/dev/null || echo 'unknown')"
ok "PHP binary : ${PHP_BIN}"
ok "PHP version: ${PHP_VER}"

# ── Buat logs directory ───────────────────────────────────────────────────────
head "Persiapan"
LOG_DIR="${SCRIPT_DIR}/redirect/logs"
if [[ ! -d "$LOG_DIR" ]]; then
    mkdir -p "$LOG_DIR"
    ok "Dibuat: ${LOG_DIR}"
else
    ok "Sudah ada: ${LOG_DIR}"
fi

# ── Verifikasi scripts ada ────────────────────────────────────────────────────
CLEANUP_SCRIPT="${SCRIPT_DIR}/redirect/cleanup-cache.php"
GEOIP_SCRIPT="${SCRIPT_DIR}/redirect/update-geoip.php"

for script in "$CLEANUP_SCRIPT" "$GEOIP_SCRIPT"; do
    if [[ -f "$script" ]]; then
        ok "Ditemukan: $(basename "$script")"
    else
        warn "Script tidak ditemukan: ${script}"
    fi
done

# ── Define cron jobs ──────────────────────────────────────────────────────────
head "Mendaftarkan Cron Jobs"

if [[ "$DRY_RUN" == true ]]; then
    warn "Mode DRY-RUN — tidak ada perubahan yang disimpan"
fi

# Job 1 — Cache cleanup setiap hari jam 02:00
add_cron \
    "0 2 * * *" \
    "\"${PHP_BIN}\" \"${CLEANUP_SCRIPT}\"" \
    "Cache cleanup (daily 02:00)" \
    "${LOG_DIR}/cache-cleanup.log"

# Job 2 — GeoIP update setiap Rabu jam 03:00
add_cron \
    "0 3 * * 3" \
    "\"${PHP_BIN}\" \"${GEOIP_SCRIPT}\"" \
    "GeoIP update (Wed 03:00)" \
    "${LOG_DIR}/geoip-update.log"

# ── Verifikasi hasil ──────────────────────────────────────────────────────────
head "Crontab saat ini"
echo ""
crontab -l 2>/dev/null | grep -E "cleanup-cache|update-geoip" | while read -r line; do
    echo -e "  ${CYAN}${line}${RESET}"
done || true

echo ""
ok "Selesai."
echo ""
echo -e "  Log files:"
echo -e "    ${LOG_DIR}/cache-cleanup.log"
echo -e "    ${LOG_DIR}/geoip-update.log"
echo ""
echo -e "  Lihat semua cron: ${BOLD}crontab -l${RESET}"
echo ""
