#!/bin/bash
# ==========================================
# AEA SERVER MODULE: OUTLINE VPN COMMANDER
# VERSION: 1.10 (Dynamic CDN Mirror Integration)
# ==========================================
AEA_VERSION="1.10"
MODULE_DATE="2026-03-29"

INFO_FILE="/etc/aea_outline.info"

# Injected by Android
API_PORT="{{APP_PORT_OUTLINE_API}}"
KEYS_PORT="{{APP_PORT_OUTLINE_KEYS}}"
TG_TOKEN="{{APP_TG_TOKEN}}"
TG_CHAT="{{APP_TG_CHAT}}"
AEA_MIRROR_URL="{{AEA_MIRROR_URL}}"

# Если Android не передал зеркало (предохранитель), используем дефолтное
if [[ "$AEA_MIRROR_URL" == "{{"* ]]; then
    AEA_MIRROR_URL="https://download.aea-aiserver.ru/mirror"
fi

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

# 2. INFO MODE (Returns the Outline API keys to Android app)
if [ "$1" == "--info" ]; then
    if [ -f "$INFO_FILE" ]; then
        cat "$INFO_FILE"
    else
        echo '{"status": "not_installed"}'
    fi
    exit 0
fi

# 3. CLI API WRAPPER (Local commands for App/SSH)
if [ "$1" == "--cli" ]; then
    if [ ! -f "$INFO_FILE" ]; then echo "[AEA] Error: Outline is not installed."; exit 1; fi
    API_URL=$(grep -o '"apiUrl":"[^"]*"' "$INFO_FILE" | cut -d'"' -f4)
    
    case $2 in
        keys) curl -sk "$API_URL/access-keys" | jq . || curl -sk "$API_URL/access-keys"; echo "" ;;
        create) curl -sk -X POST "$API_URL/access-keys"; echo "" ;;
        delete) curl -sk -X DELETE "$API_URL/access-keys/$3"; echo "[AEA] Key $3 deleted." ;;
        limits) curl -sk -X PUT -H "Content-Type: application/json" -d "{\"limit\": {\"bytes\": $4}}" "$API_URL/access-keys/$3/data-limit"; echo "[AEA] Limit set for $3" ;;
        *) echo "[AEA] Usage: aea_outline --cli [keys | create | delete <id> | limits <id> <bytes>]" ;;
    esac
    exit 0
fi

# ==========================================
# 4. METRICS MODE (Queries Prometheus for Android App)
# ==========================================
if [ "$1" == "--metrics" ]; then
    HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:9090/-/healthy)
    
    if [ "$HTTP_STATUS" -ne 200 ]; then
        echo '{"status": "error", "message": "Prometheus is offline or not installed"}'
        exit 1
    fi

    DAY_DATA=$(curl -s -g 'http://localhost:9090/api/v1/query?query=sum(increase(shadowsocks_data_bytes[1d]))by(access_key)')
    MONTH_DATA=$(curl -s -g 'http://localhost:9090/api/v1/query?query=sum(increase(shadowsocks_data_bytes[30d]))by(access_key)')
    TCP_DATA=$(curl -s -g 'http://localhost:9090/api/v1/query?query=increase(shadowsocks_tcp_connections_opened[1d])')

    [ -z "$DAY_DATA" ] && DAY_DATA="null"
    [ -z "$MONTH_DATA" ] && MONTH_DATA="null"
    [ -z "$TCP_DATA" ] && TCP_DATA="null"

    echo "{"
    echo "  \"status\": \"success\","
    echo "  \"day_traffic\": $DAY_DATA,"
    echo "  \"month_traffic\": $MONTH_DATA,"
    echo "  \"tcp_connections\": $TCP_DATA"
    echo "}"
    exit 0
fi

# 5. WATCHDOG DAEMON (Triggered by Cron)
if [ "$1" == "--run" ]; then
    if command -v docker >/dev/null 2>&1; then
        if ! docker ps --format '{{.Names}}' | grep -q "^shadowbox$"; then
            echo "[AEA] Shadowbox is down! Restarting..."
            systemctl restart docker
            docker start shadowbox >/dev/null 2>&1
            
            if [ -n "$TG_TOKEN" ] && [ "$TG_TOKEN" != "{{APP_TG_TOKEN}}" ]; then
                curl -s -X POST "https://api.telegram.org/bot$TG_TOKEN/sendMessage" \
                    -d "chat_id=$TG_CHAT" -d "text=⚠️ Outline VPN crashed and was auto-restarted on $(hostname)." -o /dev/null
            fi
        fi
    fi
    exit 0
fi

# 6. REMOVE MODE
if [ "$1" == "--remove" ]; then
    echo "[AEA] Removing Outline VPN components..."
    if command -v docker >/dev/null 2>&1; then
        docker stop shadowbox watchtower prometheus >/dev/null 2>&1
        docker rm shadowbox watchtower prometheus >/dev/null 2>&1
    fi
    rm -f "$INFO_FILE"
    rm -rf /etc/aea_outline
    if command -v ufw >/dev/null 2>&1; then
        ufw delete allow "$API_PORT"/tcp >/dev/null 2>&1
        ufw delete allow "$KEYS_PORT"/tcp >/dev/null 2>&1
        ufw delete allow "$KEYS_PORT"/udp >/dev/null 2>&1
    fi
    crontab -l | grep -v "/usr/local/bin/aea_outline --run" | crontab -
    echo "[AEA] Outline VPN successfully removed."
    exit 0
fi

# ==========================================
# 7. INSTALLATION MODE
# ==========================================
echo "[AEA] Configuring Outline VPN Commander (v$AEA_VERSION)..."

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

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

if ! command -v docker >/dev/null 2>&1; then
    echo "[AEA] Installing Docker Core..."
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -yq >/dev/null 2>&1
    apt-get install -yq curl jq docker.io >/dev/null 2>&1
    systemctl enable --now docker >/dev/null 2>&1
fi

if command -v ufw >/dev/null 2>&1; then
    echo "[AEA] Opening Firewall ports (API: $API_PORT, VPN: $KEYS_PORT)..."
    ufw allow "$API_PORT"/tcp >/dev/null 2>&1
    ufw allow "$KEYS_PORT"/tcp >/dev/null 2>&1
    ufw allow "$KEYS_PORT"/udp >/dev/null 2>&1
fi

if ! docker ps -a --format '{{.Names}}' | grep -q "^shadowbox$"; then
    
    # ============================================================
    # УМНАЯ ЗАГРУЗКА ИЗ ДИНАМИЧЕСКОГО ЗЕРКАЛА
    # ============================================================
    TAR_FILE="outline_server.tar.gz"
    echo "[AEA] Attempting to fetch components from AEA Mirror: $AEA_MIRROR_URL..."
    
    if wget -q --spider "$AEA_MIRROR_URL/$TAR_FILE"; then
        echo "[AEA] Mirror is online. Downloading archive..."
        wget -qO "$TAR_FILE" "$AEA_MIRROR_URL/$TAR_FILE"
        echo "[AEA] Pre-loading Docker images to bypass blocks..."
        docker load -i "$TAR_FILE" >/dev/null 2>&1
        rm -f "$TAR_FILE"
    else
        echo "[AEA] Mirror unreachable or file missing. Falling back to public repositories..."
    fi
    # ============================================================

    echo "[AEA] Deploying Outline server (Generating keys and configs)..."
    OUTLINE_LOG=$(mktemp)
    curl -sSL https://raw.githubusercontent.com/Jigsaw-Code/outline-server/master/src/server_manager/install_scripts/install_server.sh | bash -s -- --api-port "$API_PORT" --keys-port "$KEYS_PORT" > "$OUTLINE_LOG" 2>&1
    
    API_KEYS=$(grep -Eo '\{"apiUrl":"https://[^"]+","certSha256":"[^"]+"\}' "$OUTLINE_LOG" | head -n 1)
    
    if [ -n "$API_KEYS" ]; then
        echo "$API_KEYS" > "$INFO_FILE"
        echo "[AEA] Outline VPN successfully deployed!"
        
        if [ -n "$TG_TOKEN" ] && [ "$TG_TOKEN" != "{{APP_TG_TOKEN}}" ]; then
            CLEAN_URL=$(echo "$API_KEYS" | grep -o '"apiUrl":"[^"]*"' | cut -d'"' -f4)
            MSG="✅ Outline VPN successfully deployed on $(hostname)!%0A%0A🔑 API Port: $API_PORT%0A🛡 VPN Port: $KEYS_PORT%0A%0A📡 Management URL has been saved to the system."
            curl -s -X POST "https://api.telegram.org/bot$TG_TOKEN/sendMessage" -d "chat_id=$TG_CHAT" -d "text=$MSG" -o /dev/null
        fi
    else
        echo "[AEA] WARNING: Failed to extract API keys. Fallback required."
        echo '{"status": "error_extracting_keys"}' > "$INFO_FILE"
    fi
    rm -f "$OUTLINE_LOG"
else
    echo "[AEA] Outline VPN is already installed and running."
fi

# ==========================================
# 8. PROMETHEUS ANALYTICS ENGINE (Auto-Deploy)
# ==========================================
if command -v docker >/dev/null 2>&1; then
    if docker ps -a --format '{{.Names}}' | grep -q "^prometheus$"; then
        echo "[AEA] Prometheus container already exists. Skipping deployment."
    elif ss -tuln | grep -q ":9090 " || netstat -tuln | grep -q ":9090 "; then
        echo "[AEA] Port 9090 is already in use. Skipping Prometheus deployment."
    else
        echo "[AEA] Deploying Prometheus for advanced traffic analytics..."
        mkdir -p /etc/aea_outline
        
        METRICS_PORT=$(grep "metrics_port" /opt/outline/access.txt 2>/dev/null | cut -d':' -f2 | tr -d ' }",')
        METRICS_PORT=${METRICS_PORT:-9091}
        
        cat <<EOF > /etc/aea_outline/prometheus.yml
global:
  scrape_interval: 15s
scrape_configs:
  - job_name: 'ss-server'
    static_configs:
      - targets: ['127.0.0.1:$METRICS_PORT']
EOF
            
        docker run -d --name prometheus --restart always --network host \
            -v /etc/aea_outline/prometheus.yml:/etc/prometheus/prometheus.yml \
            prom/prometheus >/dev/null 2>&1
            
        echo "[AEA] Prometheus engine successfully deployed on port 9090."
    fi
fi

echo "[AEA] Installation complete. Telegram notification sent."
exit 0
