#!/usr/bin/env bash
# Setup cron job for automated storage monitoring

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
MONITOR_SCRIPT="${PROJECT_ROOT}/scripts/storage-monitor.sh"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }

# Check if script exists
if [ ! -f "$MONITOR_SCRIPT" ]; then
    log_warn "Monitoring script not found: $MONITOR_SCRIPT"
    exit 1
fi

# Make sure script is executable
chmod +x "$MONITOR_SCRIPT"

# Cron schedule (every hour)
CRON_SCHEDULE="0 * * * *"
CRON_COMMAND="$MONITOR_SCRIPT check >> ${PROJECT_ROOT}/logs/storage-monitoring/cron.log 2>&1"

# Check if cron job already exists
if crontab -l 2>/dev/null | grep -q "$MONITOR_SCRIPT"; then
    log_warn "Cron job already exists for storage monitoring"
    echo ""
    echo "Current cron jobs:"
    crontab -l | grep "$MONITOR_SCRIPT"
    echo ""
    
    # Check for --yes flag for non-interactive mode
    local auto_replace=false
    if [[ "${1:-}" == "--yes" ]] || [[ "${1:-}" == "-y" ]]; then
        auto_replace=true
        log_info "Auto-replace mode enabled"
    fi
    
    if [ "$auto_replace" = false ]; then
        read -p "Replace existing cron job? (yes/no): " replace
        if [ "$replace" != "yes" ]; then
            log_info "Keeping existing cron job"
            exit 0
        fi
    fi
    # Remove existing cron job
    crontab -l 2>/dev/null | grep -v "$MONITOR_SCRIPT" | crontab -
fi

# Add cron job
(crontab -l 2>/dev/null; echo "$CRON_SCHEDULE $CRON_COMMAND") | crontab -

log_success "Storage monitoring cron job added"
log_info "Schedule: Every hour"
log_info "Command: $MONITOR_SCRIPT check"
log_info "Logs: ${PROJECT_ROOT}/logs/storage-monitoring/"
echo ""
echo "To view cron jobs: crontab -l"
echo "To remove cron job: crontab -e (then delete the line)"
