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

INFO_FILE="/etc/aea_amnezia.info"

# Базовые стартовые порты (будут заменены Android-приложением)
BASE_API_PORT="{{APP_PORT_AMNEZIA_API}}"
BASE_VPN_PORT="{{APP_PORT_AMNEZIA_VPN}}"
AEA_MIRROR_URL="{{AEA_MIRROR_URL}}"

# Предохранители
[[ "$BASE_API_PORT" == "{{"* ]] && BASE_API_PORT=47560
[[ "$BASE_VPN_PORT" == "{{"* ]] && BASE_VPN_PORT=47561
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 decrypted JSON for Android app)
if [ "$1" == "--info" ]; then
    if [ -f "$INFO_FILE" ]; then
        base64 -d "$INFO_FILE"
    else
        echo '{"status": "not_installed"}'
    fi
    exit 0
fi

# 3. REMOVE MODE (Умное удаление с чисткой фаервола)
if [ "$1" == "--remove" ]; then
    echo "[AEA] Removing AmneziaWG components..."
    if [ -f "$INFO_FILE" ]; then
        JSON=$(base64 -d "$INFO_FILE")
        OLD_API=$(echo "$JSON" | grep -oP '"api_port": \K\d+')
        OLD_VPN=$(echo "$JSON" | grep -oP '"vpn_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
            [ -n "$OLD_VPN" ] && ufw delete allow "$OLD_VPN"/udp >/dev/null 2>&1
        fi
    fi

    docker stop amnezia-wg >/dev/null 2>&1
    docker rm amnezia-wg >/dev/null 2>&1
    rm -rf ~/.amnezia-wg-easy
    rm -f "$INFO_FILE"
    echo "[AEA] Module successfully removed."
    exit 0
fi

# ==========================================
# 4. INSTALLATION MODE (Runs on deploy)
# ==========================================
echo "[AEA] Initializing AmneziaWG module deployment..."

API_PORT=$BASE_API_PORT
VPN_PORT=$BASE_VPN_PORT

# --- УМНЫЙ ПОИСК СВОБОДНЫХ ПОРТОВ ---
while ss -tuln | grep -q ":$API_PORT " || netstat -tuln | grep -q ":$API_PORT "; do
    echo "[AEA] Port $API_PORT is busy. Shifting to $((API_PORT + 100))...."
    API_PORT=$((API_PORT + 100))
done

while ss -tuln | grep -q ":$VPN_PORT " || netstat -tuln | grep -q ":$VPN_PORT "; do
    echo "[AEA] Port $VPN_PORT is busy. Shifting to $((VPN_PORT + 100))...."
    VPN_PORT=$((VPN_PORT + 100))
done

# --- ПРОВЕРКА СИСТЕМНОГО ОКРУЖЕНИЯ (Docker) ---
if ! command -v docker >/dev/null 2>&1; then
    echo "[AEA] Installing container environment..."
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -yq >/dev/null 2>&1
    apt-get install -yq docker.io curl wget >/dev/null 2>&1
    systemctl enable --now docker >/dev/null 2>&1
fi

# --- УСТАНОВКА И АКТИВАЦИЯ ЯДРА WIREGUARD ---
echo "[AEA] Installing WireGuard kernel module..."
export DEBIAN_FRONTEND=noninteractive
apt-get update -yq >/dev/null 2>&1
apt-get install -yq wireguard >/dev/null 2>&1
modprobe wireguard

PUBLIC_IP=$(curl -s ifconfig.me)

# --- ВКЛЮЧЕНИЕ МАРШРУТИЗАЦИИ (IP FORWARDING) НА ХОСТЕ ---
echo "[AEA] Enabling IP routing (forwarding)..."
echo "net.ipv4.ip_forward = 1" > /etc/sysctl.d/99-amnezia-forward.conf
sysctl -p /etc/sysctl.d/99-amnezia-forward.conf >/dev/null 2>&1

# ============================================================
# УМНАЯ ЗАГРУЗКА ИЗ ДИНАМИЧЕСКОГО ЗЕРКАЛА
# ============================================================
TAR_FILE="amnezia_wg_easy.tar.gz"
echo "[AEA] Attempting to fetch AmneziaWG 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/spcfox/amnezia-wg-easy:latest >/dev/null 2>&1
fi
# ============================================================

# --- ГЕНЕРАЦИЯ ПАРОЛЯ И ХЭША ---
echo "[AEA] Generating secure administrative password..."
PASS=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1)

echo "[AEA] Generating password hash via Amnezia container..."
PASS_HASH=$(docker run --rm ghcr.io/spcfox/amnezia-wg-easy:latest wgeasy hashow "$PASS" 2>/dev/null | tail -n 1)

# --- НАСТРОЙКА UFW (ФАЕРВОЛ) ---
if command -v ufw >/dev/null 2>&1; then
    echo "[AEA] Configuring system firewall for allocated ports and routing..."
    ufw allow "$API_PORT"/tcp >/dev/null 2>&1
    ufw allow "$VPN_PORT"/udp >/dev/null 2>&1
    
    sed -i 's/DEFAULT_FORWARD_POLICY="DROP"/DEFAULT_FORWARD_POLICY="ACCEPT"/g' /etc/default/ufw
    ufw reload >/dev/null 2>&1
fi

# --- ЗАПУСК МОДУЛЯ ---
echo "[AEA] Starting VPN container..."
docker rm -f amnezia-wg >/dev/null 2>&1

docker run -d \
  --name amnezia-wg \
  -e WG_HOST="$PUBLIC_IP" \
  -e WG_PORT="$VPN_PORT" \
  -e PASSWORD_HASH="$PASS_HASH" \
  -e WG_DEFAULT_ADDRESS="10.8.0.x" \
  -e WG_DEFAULT_DNS="1.1.1.1" \
  -e WG_ALLOWED_IPS="0.0.0.0/0" \
  -v ~/.amnezia-wg-easy:/etc/wireguard \
  -p "$VPN_PORT":51820/udp \
  -p "$API_PORT":51821/tcp \
  --cap-add=NET_ADMIN \
  --cap-add=SYS_MODULE \
  --sysctl="net.ipv4.conf.all.src_valid_mark=1" \
  --sysctl="net.ipv4.ip_forward=1" \
  --device=/dev/net/tun \
  --privileged \
  --restart always \
  ghcr.io/spcfox/amnezia-wg-easy:latest >/dev/null 2>&1

# --- ШИФРОВАНИЕ И СОХРАНЕНИЕ ДАННЫХ ---
echo "[AEA] Securing access credentials..."
JSON_DATA="{\"status\": \"success\", \"api_port\": $API_PORT, \"vpn_port\": $VPN_PORT, \"password\": \"$PASS\"}"

echo "$JSON_DATA" | base64 > "$INFO_FILE"
chmod 600 "$INFO_FILE"

# --- КОПИРОВАНИЕ СЕБЯ В СИСТЕМУ ---
MODULE_PATH="/usr/local/bin/aea_amnezia_wg"
cat "$0" > "$MODULE_PATH"
chmod +x "$MODULE_PATH"

echo "[AEA] Module successfully deployed! API: $API_PORT (TCP), VPN: $VPN_PORT (UDP)."
exit 0
