#!/bin/bash
# ==========================================
# AEA SERVER MODULE: NOTIFIER COMMANDER
# VERSION: 1.10
# ==========================================
AEA_VERSION="1.10"
MODULE_DATE="2026-03-10"

CONF_FILE="/etc/aea_notifier.conf"

# 1. Version check for Android app
if [ "$1" == "--version" ] || [ "$1" == "-v" ]; then
    echo "$AEA_VERSION"
    exit 0
fi

# 2. Create default config if it doesn't exist
if [ ! -f "$CONF_FILE" ]; then
    cat << 'EOF' > "$CONF_FILE"
TG_TOKEN=""
TG_CHAT=""
USER_EMAIL=""
CHECK_HARDWARE="1"
THRESH_DISK="90"
CHECK_DB_MYSQL="1"
CHECK_SECURITY_SSH="1"
EOF
fi

# 3. CONFIGURATION MODE (Triggered from Android via commands)
if [ "$1" == "--config" ]; then
    shift
    echo "[AEA] Updating Notifier configuration..."
    while [[ "$#" -gt 0 ]]; do
        case $1 in
            --tg)
                sed -i "s/^TG_TOKEN=.*/TG_TOKEN=\"$2\"/" "$CONF_FILE"
                sed -i "s/^TG_CHAT=.*/TG_CHAT=\"$3\"/" "$CONF_FILE"
                echo "[AEA] Telegram credentials updated."
                shift 3
                ;;
            --email)
                sed -i "s/^USER_EMAIL=.*/USER_EMAIL=\"$2\"/" "$CONF_FILE"
                shift 2
                ;;
            --disk)
                sed -i "s/^THRESH_DISK=.*/THRESH_DISK=\"$2\"/" "$CONF_FILE"
                sed -i "s/^CHECK_HARDWARE=.*/CHECK_HARDWARE=\"1\"/" "$CONF_FILE"
                echo "[AEA] Disk threshold set to $2%."
                shift 2
                ;;
            --mysql)
                sed -i "s/^CHECK_DB_MYSQL=.*/CHECK_DB_MYSQL=\"$2\"/" "$CONF_FILE"
                echo "[AEA] MySQL checking set to $2."
                shift 2
                ;;
            --ssh-guard)
                sed -i "s/^CHECK_SECURITY_SSH=.*/CHECK_SECURITY_SSH=\"$2\"/" "$CONF_FILE"
                echo "[AEA] SSH guard set to $2."
                shift 2
                ;;
            *)
                echo "[AEA] Unknown parameter: $1"
                shift
                ;;
        esac
    done
    exit 0
fi

# 4. EXECUTION MODE (Triggered by Cron every 5 minutes)
if [ "$1" == "--run" ]; then
    source "$CONF_FILE"

    send_alert() {
        local subject="$1"
        local message="$2"
        if [ -n "$TG_TOKEN" ] && [ -n "$TG_CHAT" ]; then
            curl -s -X POST "https://api.telegram.org/bot$TG_TOKEN/sendMessage" \
                -d "chat_id=$TG_CHAT" -d "text=🚨 $subject%0A$message" -o /dev/null
        fi
        if [ -n "$USER_EMAIL" ] && command -v mail >/dev/null 2>&1; then
            CLEAN_EMAILS=$(echo "$USER_EMAIL" | tr ',' ' ')
            echo "$message" | mail -s "AEA ALERT: $subject" $CLEAN_EMAILS
        fi
    }

    if [ "$CHECK_HARDWARE" = "1" ]; then
        DISK_USAGE=$(df / | grep -w / | awk '{ print $5}' | sed 's/%//g')
        if [ -n "$THRESH_DISK" ] && [ "$DISK_USAGE" -gt "$THRESH_DISK" ]; then
            send_alert "Disk Space Alert" "Critical: $DISK_USAGE% used on $(hostname)."
        fi
    fi

    if [ "$CHECK_DB_MYSQL" = "1" ]; then
        if systemctl list-unit-files | grep -qE '^mysql|^mariadb'; then
            if ! systemctl is-active --quiet mysql && ! systemctl is-active --quiet mariadb; then
                send_alert "Database Alert" "MySQL/MariaDB service is STOPPED on $(hostname)!"
            fi
        fi
    fi

    if [ "$CHECK_SECURITY_SSH" = "1" ]; then
        LOG_FILE_AUTH="/var/log/auth.log"
        [ ! -f "$LOG_FILE_AUTH" ] && LOG_FILE_AUTH="/var/log/secure"
        if [ -f "$LOG_FILE_AUTH" ]; then
            FAILED=$(find "$LOG_FILE_AUTH" -mmin -10 -type f -exec grep -c "Failed password" {} + | awk '{s+=$1} END {print s}')
            if [ -n "$FAILED" ] && [ "$FAILED" -gt 5 ]; then
                send_alert "SSH Security Alert" "Detected $FAILED failed login attempts in 10 mins on $(hostname)."
            fi
        fi
    fi
    exit 0
fi

# 5. INSTALLATION MODE
echo "[AEA] Installing Notifier Commander module (v$AEA_VERSION)..."
MODULE_PATH="/usr/local/bin/aea_notifier"
cat "$0" > "$MODULE_PATH"
chmod +x "$MODULE_PATH"

if ! crontab -l 2>/dev/null | grep -q "$MODULE_PATH --run"; then
    echo "[AEA] Configuring Cron schedule (every 5 minutes)..."
    (crontab -l 2>/dev/null; echo "*/5 * * * * $MODULE_PATH --run >/dev/null 2>&1") | crontab -
fi

echo "[AEA] Module successfully installed! Use 'aea_notifier --config' to set it up."
exit 0
