#!/bin/bash
# ==========================================
# AEA SERVER MODULE: HYSTERIA 2 COMMANDER
# VERSION: 1.01 (Dynamic CDN Mirror Integration)
# ==========================================
AEA_VERSION="1.01"
MODULE_DATE="2026-04-26"

INFO_FILE="/etc/aea_hysteria.info"
DATA_DIR="/etc/hysteria"

AEA_MIRROR_URL="{{AEA_MIRROR_URL}}"
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 (Smart cleanup)
if [ "$1" == "--remove" ]; then
    echo "[AEA] Removing Hysteria 2 components..."
    
    # Read old port and close UFW
    if [ -f "$INFO_FILE" ]; then
        JSON=$(base64 -d "$INFO_FILE")
        OLD_PORT=$(echo "$JSON" | grep -oP '"port": \K\d+')
        if command -v ufw >/dev/null 2>&1; then
            [ -n "$OLD_PORT" ] && ufw delete allow "$OLD_PORT"/udp >/dev/null 2>&1
        fi
    fi

    systemctl stop hysteria-server.service >/dev/null 2>&1
    systemctl disable hysteria-server.service >/dev/null 2>&1
    rm -f /etc/systemd/system/hysteria-server.service
    systemctl daemon-reload

    rm -f /usr/local/bin/hysteria
    rm -rf "$DATA_DIR"
    rm -f "$INFO_FILE"
    
    echo "[AEA] Module successfully removed."
    exit 0
fi

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

# --- GENERATE RANDOM PORT AND PASSWORD ---
PORT=$(shuf -i 10000-50000 -n 1)

while ss -tuln | grep -q ":$PORT " || netstat -tuln | grep -q ":$PORT "; do
    PORT=$(shuf -i 10000-50000 -n 1)
done

echo "[AEA] Generating secure password and self-signed certificate..."
PASS=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1)

mkdir -p "$DATA_DIR"
cd "$DATA_DIR"

# Generate self-signed cert masquerading as bing.com
openssl ecparam -genkey -name prime256v1 -out "$DATA_DIR/server.key" 2>/dev/null
openssl req -new -x509 -days 3650 -key "$DATA_DIR/server.key" -out "$DATA_DIR/server.crt" -subj "/CN=bing.com" 2>/dev/null

# --- CREATE CONFIG.YAML ---
cat <<EOF > "$DATA_DIR/config.yaml"
listen: :$PORT

tls:
  cert: $DATA_DIR/server.crt
  key: $DATA_DIR/server.key

auth:
  type: password
  password: $PASS

masquerade:
  type: proxy
  proxy:
    url: https://bing.com/
    rewriteHost: true
EOF

# --- DOWNLOAD BINARY ---
echo "[AEA] Setting up system environment for module..."
export DEBIAN_FRONTEND=noninteractive
apt-get update -yq >/dev/null 2>&1
apt-get install -yq curl wget tar >/dev/null 2>&1

ARCH=$(uname -m)
DOWNLOAD_SUCCESS=false

# ============================================================
# УМНАЯ ЗАГРУЗКА ИЗ ДИНАМИЧЕСКОГО ЗЕРКАЛА
# ============================================================
echo "[AEA] Attempting to fetch Hysteria 2 binary from AEA Mirror: $AEA_MIRROR_URL..."

if [ "$ARCH" == "x86_64" ]; then
    TAR_FILE="hysteria2_amd64.tar.gz"
    if wget -q --spider "$AEA_MIRROR_URL/$TAR_FILE"; then
        echo "[AEA] Mirror is online. Downloading archive..."
        wget -qO "/tmp/$TAR_FILE" "$AEA_MIRROR_URL/$TAR_FILE"
        echo "[AEA] Extracting binary to system..."
        tar -xzf "/tmp/$TAR_FILE" -C /usr/local/bin/ >/dev/null 2>&1
        rm -f "/tmp/$TAR_FILE"
        if [ -f "/usr/local/bin/hysteria" ]; then
            DOWNLOAD_SUCCESS=true
        fi
    fi
else
    echo "[AEA] Architecture is $ARCH. Skipping mirror (AMD64 only)."
fi
# ============================================================

# ФОЛЛБЕК НА ОРИГИНАЛ (Если зеркало упало или процессор ARM)
if [ "$DOWNLOAD_SUCCESS" = false ]; then
    echo "[AEA] Mirror unreachable or unsupported architecture. Falling back to public GitHub registry..."
    case "$ARCH" in
        x86_64) DL_URL="https://github.com/apernet/hysteria/releases/latest/download/hysteria-linux-amd64" ;;
        aarch64|arm64) DL_URL="https://github.com/apernet/hysteria/releases/latest/download/hysteria-linux-arm64" ;;
        *) echo "[AEA] Unsupported architecture: $ARCH"; exit 1 ;;
    esac
    wget -qO /usr/local/bin/hysteria "$DL_URL"
fi

chmod +x /usr/local/bin/hysteria

# --- CONFIGURE FIREWALL ---
if command -v ufw >/dev/null 2>&1; then
    echo "[AEA] Configuring system firewall for allocated port..."
    ufw allow "$PORT"/udp >/dev/null 2>&1
fi

# --- CREATE SYSTEMD SERVICE ---
cat <<EOF > /etc/systemd/system/hysteria-server.service
[Unit]
Description=Hysteria 2 Server
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/hysteria server -c $DATA_DIR/config.yaml
Restart=on-failure
RestartSec=3
LimitNOFILE=infinity

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload >/dev/null 2>&1
systemctl enable --now hysteria-server.service >/dev/null 2>&1

# --- ENCRYPT AND SAVE INFO FOR ANDROID ---
echo "[AEA] Securing access credentials..."
JSON_DATA="{\"status\": \"success\", \"port\": $PORT, \"password\": \"$PASS\"}"

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

# --- COPY ITSELF AS SYSTEM COMMAND ---
MODULE_PATH="/usr/local/bin/aea_hysteria2"
cat "$0" > "$MODULE_PATH"
chmod +x "$MODULE_PATH"

echo "[AEA] Module successfully deployed! UDP Port: $PORT."
exit 0
