#!/bin/bash
# ==========================================
# AEA SERVER MODULE: AUTO UPDATER
# VERSION: 1.08
# ==========================================
AEA_VERSION="1.08"
MODULE_DATE="2026-03-10"

CONF_FILE="/etc/aea_auto_updater.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=""
EOF
fi

# 3. CONFIGURATION MODE (Triggered from Android via commands)
if [ "$1" == "--config" ]; then
    shift
    echo "[AEA] Updating Auto Updater 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
                ;;
            *)
                echo "[AEA] Unknown parameter: $1"
                shift
                ;;
        esac
    done
    exit 0
fi

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

    # Force non-interactive mode to prevent upgrade prompts from freezing the system
    export DEBIAN_FRONTEND=noninteractive

    # Perform silent updates
    apt-get update -yq >/dev/null 2>&1
    apt-get -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" upgrade -yq >/dev/null 2>&1

    # Check if system reboot is required
    REBOOT_REQUIRED=false
    if [ -f /var/run/reboot-required ]; then
        REBOOT_REQUIRED=true
    fi

    # Send Telegram report
    if [ -n "$TG_TOKEN" ] && [ -n "$TG_CHAT" ]; then
        MSG="✅ Server $(hostname) has been successfully updated."
        if [ "$REBOOT_REQUIRED" = "true" ]; then
            MSG="$MSG%0A⚠️ Manual system reboot is required!"
        fi
        curl -s -X POST "https://api.telegram.org/bot$TG_TOKEN/sendMessage" \
             -d "chat_id=$TG_CHAT" -d "text=$MSG" -o /dev/null
    fi

    exit 0
fi

# 5. INSTALLATION MODE (Triggered from Android)
echo "[AEA] Installing Auto Updater module (v$AEA_VERSION)..."
echo "[AEA] Setting up system environment for automated updates..."

MODULE_PATH="/usr/local/bin/aea_auto_updater"
cat "$0" > "$MODULE_PATH"
chmod +x "$MODULE_PATH"

# Self-scheduling module to run every night at 04:00 AM
if ! crontab -l 2>/dev/null | grep -q "$MODULE_PATH --run"; then
    echo "[AEA] Configuring Cron schedule (Daily at 04:00 AM)..."
    (crontab -l 2>/dev/null; echo "0 4 * * * $MODULE_PATH --run >/dev/null 2>&1") | crontab -
fi

echo "[AEA] Module successfully installed! It will run updates daily at 04:00 AM."
echo "[AEA] Use 'aea_auto_updater --config --tg <TOKEN> <CHAT_ID>' to set up Telegram alerts."
exit 0
