#!/bin/bash
########################################
# Disk Space Monitor
# Alerts when disk space is low
# Run via cron every 5 minutes
########################################

# Get the directory where this script lives
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
LOG_FILE="$PROJECT_ROOT/storage/logs/disk-space-monitor.log"
ALERT_FILE="$PROJECT_ROOT/storage/logs/disk-space-alerts.log"

# Alert thresholds
CRITICAL_THRESHOLD=90  # Alert at 90% full
WARNING_THRESHOLD=80   # Warn at 80% full

# Email settings (set in .env or here)
ALERT_EMAIL="${DISK_SPACE_ALERT_EMAIL:-admin@globalgala.com}"

# Load cron context library
source "$SCRIPT_DIR/_cron-context.sh" 2>/dev/null || true

# Change to project directory
cd "$PROJECT_ROOT" || exit 1

# Function to log with timestamp
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

# Function to send alert
send_alert() {
    local severity=$1
    local message=$2

    log "$severity: $message"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $severity: $message" >> "$ALERT_FILE"

    # Send email if mail command is available
    if command -v mail >/dev/null 2>&1; then
        echo "$message" | mail -s "[$severity] Disk Space Alert - Global Gala" "$ALERT_EMAIL"
    fi

    # Log to Laravel if possible
    if [ -f "$PROJECT_ROOT/artisan" ]; then
        php artisan tinker --execute="
            \Log::${severity,,}('Disk space alert', [
                'message' => '$message',
                'timestamp' => now()
            ]);
        " 2>/dev/null
    fi
}

# Get disk usage for root partition
get_disk_usage() {
    df -h / | awk 'NR==2 {print $5}' | sed 's/%//'
}

# Get disk usage details
get_disk_details() {
    df -h / | awk 'NR==2 {print "Total: " $2 " | Used: " $3 " | Available: " $4 " | Use%: " $5}'
}

# Main monitoring logic
main() {
    USAGE=$(get_disk_usage)
    DETAILS=$(get_disk_details)

    log "Disk usage check: ${USAGE}% - ${DETAILS}"

    if [ "$USAGE" -ge "$CRITICAL_THRESHOLD" ]; then
        # Output context for critical email
        get_cron_context "$PROJECT_ROOT" 2>/dev/null || true
        send_alert "CRITICAL" "Disk space critical: ${USAGE}% full. ${DETAILS}. Immediate action required!"
        cron_error "Disk space critical: ${USAGE}% full" "disk-space-monitor.sh" 2>/dev/null || true
        exit 1

    elif [ "$USAGE" -ge "$WARNING_THRESHOLD" ]; then
        # Output context for warning email
        get_cron_context "$PROJECT_ROOT" 2>/dev/null || true
        send_alert "WARNING" "Disk space warning: ${USAGE}% full. ${DETAILS}. Plan cleanup soon."
        echo "⚠️  Disk space warning: ${USAGE}% full"
        exit 0

    else
        log "Disk space healthy: ${USAGE}% full"
        # Silent success (no email)
        exit 0
    fi
}

# Run the monitor
main
