#!/bin/bash
# ==========================================
# AEA SERVER MODULE: VLESS/XRAY (3X-UI) COMMANDER
# VERSION: 1.02 (Dynamic CDN Mirror Integration)
# ==========================================
AEA_VERSION="1.02"
MODULE_DATE="2026-03-29"

INFO_FILE="/etc/aea_vless.info"
DATA_DIR="/etc/aea_3x_ui"

BASE_API_PORT="{{APP_PORT_VLESS_API}}"
[[ "$BASE_API_PORT" == "{{"* ]] && BASE_API_PORT=48562

BASE_VPN_PORT="{{APP_PORT_VLESS_VPN}}"
[[ "$BASE_VPN_PORT" == "{{"* ]] && BASE_VPN_PORT=49443

AEA_MIRROR_URL="{{AEA_MIRROR_URL}}"
if [[ "$AEA_MIRROR_URL" == "{{"* ]]; then
    AEA_MIRROR_URL="https://download.aea-aiserver.ru/mirror"
fi

if [ "$1" == "--version" ] || [ "$1" == "-v" ]; then
    echo "$AEA_VERSION"
    exit 0
fi

if [ "$1" == "--info" ]; then
    if [ -f "$INFO_FILE" ]; then
        base64 -d "$INFO_FILE"
    else
        echo '{"status": "not_installed"}'
    fi
    exit 0
fi

if [ "$1" == "--remove" ]; then
    echo "[AEA] Removing VLESS/3x-ui components..."
    if [ -f "$INFO_FILE" ]; then
        JSON=$(base64 -d "$INFO_FILE")
        OLD_API=$(echo "$JSON" | grep -oP '"api_port": \K\d+')
        if command -v ufw >/dev/null 2>&1; then
            [ -n "$OLD_API" ] && ufw delete allow "$OLD_API"/tcp >/dev/null 2>&1
            ufw delete allow "$BASE_VPN_PORT"/tcp >/dev/null 2>&1
            ufw delete allow "$BASE_VPN_PORT"/udp >/dev/null 2>&1
            # Зачищаем старые порты 443 и 80, если они были открыты ранее этим скриптом
            ufw delete allow 80/tcp >/dev/null 2>&1
            ufw delete allow 443/tcp >/dev/null 2>&1
            ufw delete allow 443/udp >/dev/null 2>&1
        fi
    fi

    docker stop aea-3x-ui >/dev/null 2>&1
    docker rm aea-3x-ui >/dev/null 2>&1
    rm -rf "$DATA_DIR"
    rm -f "$INFO_FILE"
    echo "[AEA] Module successfully removed."
    exit 0
fi

# ==========================================
# INSTALLATION MODE
# ==========================================
echo "[AEA] Initializing VLESS (3x-ui) module deployment..."
API_PORT=$BASE_API_PORT

while ss -tuln | grep -q ":$API_PORT " || netstat -tuln | grep -q ":$API_PORT "; do
    API_PORT=$((API_PORT + 10))
done

if ! command -v docker >/dev/null 2>&1; then
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -yq >/dev/null 2>&1
    apt-get install -yq docker.io curl jq wget >/dev/null 2>&1
    systemctl enable --now docker >/dev/null 2>&1
fi

PUBLIC_IP=$(curl -s ifconfig.me)

# ============================================================
# УМНАЯ ЗАГРУЗКА ИЗ ДИНАМИЧЕСКОГО ЗЕРКАЛА
# ============================================================
TAR_FILE="3x_ui.tar.gz"
echo "[AEA] Attempting to fetch VLESS panel 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 image to bypass blocks..."
    docker load -i "$TAR_FILE" >/dev/null 2>&1
    rm -f "$TAR_FILE"
else
    echo "[AEA] Mirror unreachable. Falling back to public GitHub registry..."
    docker pull -q ghcr.io/mhsanaei/3x-ui:latest >/dev/null 2>&1
fi
# ============================================================

PANEL_USER="aea_admin_$(cat /dev/urandom | tr -dc '0-9' | fold -w 4 | head -n 1)"
PANEL_PASS=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1)
SECRET_PATH="$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 12 | head -n 1)"

if command -v ufw >/dev/null 2>&1; then
    ufw allow "$API_PORT"/tcp >/dev/null 2>&1
    ufw allow "$BASE_VPN_PORT"/tcp >/dev/null 2>&1
    ufw allow "$BASE_VPN_PORT"/udp >/dev/null 2>&1
fi

docker rm -f aea-3x-ui >/dev/null 2>&1
mkdir -p "$DATA_DIR"

docker run -d \
  --name aea-3x-ui \
  --network=host \
  -e XRAY_VMESS_AEAD_FORCED=false \
  -v "$DATA_DIR":/etc/xray-ui/ \
  --restart always \
  ghcr.io/mhsanaei/3x-ui:latest >/dev/null 2>&1

echo "[AEA] Applying strict security settings to panel..."

# Умное ожидание базы данных (до 30 секунд с запасом)
echo "[AEA] Waiting for database initialization..."
for i in {1..30}; do
    if docker exec aea-3x-ui stat /etc/xray-ui/x-ui.db >/dev/null 2>&1; then
        sleep 2 # Ждем еще пару секунд для верности после создания файла
        break
    fi
    sleep 1
done

# Пробрасываем настройки напрямую в бинарник панели (/app/x-ui)
docker exec aea-3x-ui /app/x-ui setting -username "$PANEL_USER" -password "$PANEL_PASS" -port "$API_PORT" -webBasePath "/$SECRET_PATH/" >/dev/null 2>&1
docker restart aea-3x-ui >/dev/null 2>&1

JSON_DATA="{\"status\": \"success\", \"api_port\": $API_PORT, \"username\": \"$PANEL_USER\", \"password\": \"$PANEL_PASS\", \"base_path\": \"/$SECRET_PATH/\"}"
echo "$JSON_DATA" | base64 > "$INFO_FILE"
chmod 600 "$INFO_FILE"

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

# ВАЖНОЕ СООБЩЕНИЕ ДЛЯ ПОЛЬЗОВАТЕЛЯ
echo "[AEA] VLESS installation complete."
echo "==========================================================="
echo "ВНИМАНИЕ! Порт по умолчанию для VPN трафика изменен на: $BASE_VPN_PORT"
echo "Обязательно указывайте порт $BASE_VPN_PORT при создании inbounds в панели!"
echo "==========================================================="

exit 0
