#!/bin/bash
# ==============================================================================
# Wordly.art - Install Backup Crontab
# ==============================================================================
# Run ONCE to install all scheduled backup tasks.
#
# Usage:
#   bash scripts/install-crontab.sh
# ==============================================================================

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CRONTAB_FILE="${SCRIPT_DIR}/crontab.wordly"
LOG_DIR="/var/log"

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

log()         { echo "[Crontab] $1"; }
log_success() { echo -e "[Crontab] ${GREEN}✅ $1${NC}"; }
log_warning() { echo -e "[Crontab] ${YELLOW}⚠️  $1${NC}"; }

# ==============================================================================
# 1. Create the crontab file
# ==============================================================================
cat > "${CRONTAB_FILE}" <<EOF
# ==============================================================================
# Wordly.art — Backup & Disaster Recovery Crontab
# Installed by: bash scripts/install-crontab.sh
# ==============================================================================

# Backup to NAS every 6 hours (00:00, 06:00, 12:00, 18:00)
0 */6 * * * bash ${SCRIPT_DIR}/backup-to-nas.sh >> ${LOG_DIR}/wordly-backup.log 2>&1

# Verify backup integrity 30 minutes after each backup
30 */6 * * * bash ${SCRIPT_DIR}/verify-backups.sh >> ${LOG_DIR}/wordly-verify.log 2>&1

# Rotate logs weekly (keep last 30 days)
0 4 * * 0 find ${LOG_DIR} -name "wordly-*.log" -mtime +30 -delete 2>/dev/null || true
EOF

log_success "Crontab file created: ${CRONTAB_FILE}"

# ==============================================================================
# 2. Install crontab for current user
# ==============================================================================
log "Installing crontab..."

# Preserve existing crontab (if any), append new entries
EXISTING_CRON=$(crontab -l 2>/dev/null || true)

# Remove any existing wordly entries (to avoid duplicates on re-run)
EXISTING_CRON_CLEAN=$(echo "${EXISTING_CRON}" | grep -v "wordly" | grep -v "backup-to-nas" | grep -v "verify-backups" || true)

# Combine
NEW_CRON=$(printf "%s\n%s\n" "${EXISTING_CRON_CLEAN}" "$(cat "${CRONTAB_FILE}")")
echo "${NEW_CRON}" | crontab -

log_success "Crontab installed!"
echo ""
log "Current crontab:"
crontab -l | grep -E "wordly|backup|verify" | sed 's/^/  /'
echo ""
log_success "Scheduled jobs:"
log_success "  Every 6h (00:00/06:00/12:00/18:00) → backup-to-nas.sh"
log_success "  Every 6h+30min                      → verify-backups.sh"
log_success "  Every Sunday at 04:00               → log rotation"
echo ""
log_warning "Logs will be written to:"
log_warning "  ${LOG_DIR}/wordly-backup.log"
log_warning "  ${LOG_DIR}/wordly-verify.log"
