#!/usr/bin/env bash
#####################################
# Rebootless Notification System
#####################################

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BASE_DIR="$(dirname "$SCRIPT_DIR")"
CONFIG_FILE="${BASE_DIR}/rebootless.conf"

# Load config
if [[ -f "$CONFIG_FILE" ]]; then
    source "$CONFIG_FILE"
fi

# Defaults
SLACK_WEBHOOK_URL="${SLACK_WEBHOOK_URL:-}"
EMAIL_TO="${EMAIL_TO:-}"
ENABLE_NOTIFICATIONS="${ENABLE_NOTIFICATIONS:-0}"

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

usage() {
    cat <<EOF
Usage: $0 [OPTIONS] MESSAGE

Options:
  --success    Success notification (green)
  --failure    Failure notification (red)
  --info       Info notification (cyan)
  --warning    Warning notification (yellow)
  --slack      Force Slack notification
  --email      Force email notification
  -h, --help   Show this help

Examples:
  $0 --success "Build completed successfully"
  $0 --failure "Build failed at kpatch step"
  $0 --info --slack "New CVEs detected"
EOF
    exit 0
}

send_slack() {
    local message="$1"
    local color="$2"
    
    if [[ -z "$SLACK_WEBHOOK_URL" ]]; then
        echo -e "${YELLOW}Slack webhook not configured (SLACK_WEBHOOK_URL)${RESET}"
        return 1
    fi
    
    local payload=$(cat <<EOF
{
    "text": "$message",
    "attachments": [
        {
            "color": "$color",
            "fields": [
                {
                    "title": "Host",
                    "value": "$(hostname)",
                    "short": true
                },
                {
                    "title": "Time",
                    "value": "$(date '+%Y-%m-%d %H:%M:%S')",
                    "short": true
                }
            ]
        }
    ]
}
EOF
)
    
    local response=$(curl -s -X POST \
        -H 'Content-Type: application/json' \
        -d "$payload" \
        "$SLACK_WEBHOOK_URL" 2>&1) || true
    
    if [[ "$response" == "ok" ]]; then
        echo -e "${GREEN}✓ Slack notification sent${RESET}"
        return 0
    else
        echo -e "${RED}✗ Slack notification failed: $response${RESET}"
        return 1
    fi
}

send_email() {
    local subject="$1"
    local message="$2"
    
    if [[ -z "$EMAIL_TO" ]]; then
        echo -e "${YELLOW}Email not configured (EMAIL_TO)${RESET}"
        return 1
    fi
    
    if ! command -v sendmail >/dev/null 2>&1; then
        echo -e "${YELLOW}sendmail not available${RESET}"
        return 1
    fi
    
    local full_message="From: rebootless@$(hostname)
To: $EMAIL_TO
Subject: [Rebootless] $subject
Date: $(date '+%a, %d %b %Y %H:%M:%S %z')

$message

---
Rebootless Kernel Patching System
Host: $(hostname)
"
    
    echo -e "$full_message" | sendmail -t
    
    if [[ $? -eq 0 ]]; then
        echo -e "${GREEN}✓ Email notification sent to $EMAIL_TO${RESET}"
        return 0
    else
        echo -e "${RED}✗ Email notification failed${RESET}"
        return 1
    fi
}

notify() {
    local type="$1"
    local message="$2"
    local force_slack=false
    local force_email=false
    
    # Parse remaining args
    shift 2
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --slack) force_slack=true ;;
            --email) force_email=true ;;
        esac
        shift
    done
    
    # Check if notifications enabled
    if [[ "$ENABLE_NOTIFICATIONS" != "1" ]] && ! $force_slack && ! $force_email; then
        echo -e "${YELLOW}Notifications disabled (ENABLE_NOTIFICATIONS=0)${RESET}"
        return 0
    fi
    
    # Determine color and prefix
    local color=""
    local prefix=""
    case "$type" in
        success)
            color="good"
            prefix="✅"
            ;;
        failure)
            color="danger"
            prefix="❌"
            ;;
        info)
            color="#36a64f"
            prefix="ℹ️"
            ;;
        warning)
            color="warning"
            prefix="⚠️"
            ;;
    esac
    
    local full_message="$prefix $message"
    
    echo -e "${CYAN}Sending notification: ${message}${RESET}"
    
    # Send Slack
    if $force_slack || [[ "$ENABLE_NOTIFICATIONS" == "1" && -n "$SLACK_WEBHOOK_URL" ]]; then
        send_slack "$full_message" "$color" || true
    fi
    
    # Send Email
    if $force_email || [[ "$ENABLE_NOTIFICATIONS" == "1" && -n "$EMAIL_TO" ]]; then
        send_email "$type: $message" "$message" || true
    fi
}

# Main
if [[ $# -eq 0 ]]; then
    usage
fi

TYPE="info"
MESSAGE=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        --success) TYPE="success"; shift ;;
        --failure) TYPE="failure"; shift ;;
        --info) TYPE="info"; shift ;;
        --warning) TYPE="warning"; shift ;;
        --slack) shift ;;
        --email) shift ;;
        -h|--help) usage ;;
        *) MESSAGE="$1"; shift ;;
    esac
done

if [[ -z "$MESSAGE" ]]; then
    echo "Error: Message required"
    usage
fi

notify "$TYPE" "$MESSAGE" "$@"
