#!/bin/bash
#
# MCProxy Xray 一键安装脚本
# SS2022 + Minecraft Transport 伪装
# 支持：安装节点 / 端口转发（对等/异端口）
#

set -e

# ========== 管道模式检测 ==========
# curl ... | bash 时 stdin 被管道占用，read 无法交互
if [ ! -t 0 ]; then
    _TMP=$(mktemp /tmp/mcproxy-install.XXXXXX.sh)
    curl -fsSL "https://get.coexa.cx/mcproxy-install.sh" -o "$_TMP"
    chmod +x "$_TMP"
    exec bash "$_TMP" "$@"
fi

# ========== 颜色 ==========
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

info()  { echo -e "${GREEN}[INFO]${NC} $1"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

# ========== 检查 root ==========
[[ $EUID -ne 0 ]] && error "请使用 root 用户运行此脚本"

# ========== 主菜单 ==========
echo ""
echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN}  MCProxy 一键管理脚本${NC}"
echo -e "${CYAN}  SS2022 + Minecraft Transport 伪装${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""
echo -e "  ${GREEN}1)${NC} 安装 MCProxy 节点"
echo -e "  ${GREEN}2)${NC} 配置端口转发"
echo -e "  ${GREEN}3)${NC} 查看/管理端口转发"
echo -e "  ${GREEN}4)${NC} 卸载${NC}"
echo ""
printf "%b" "${GREEN}请选择 ${YELLOW}[1-4]${NC}: "
read -r CHOICE

case "$CHOICE" in
    1) ;; # 继续安装流程
    2) # 端口转发
        echo ""
        echo -e "${CYAN}===== 端口转发配置 =====${NC}"
        echo ""
        printf "%b" "${GREEN}本机监听端口${NC}: "
        read -r LOCAL_PORT
        [[ -z "$LOCAL_PORT" ]] && error "本机端口不能为空"

        printf "%b" "${GREEN}目标服务器 IP${NC}: "
        read -r TARGET_IP
        [[ -z "$TARGET_IP" ]] && error "目标 IP 不能为空"

        printf "%b" "${GREEN}目标端口 ${YELLOW}[默认: 与本机端口相同 $LOCAL_PORT]${NC}: "
        read -r TARGET_PORT
        TARGET_PORT=${TARGET_PORT:-$LOCAL_PORT}

        # 安装 socat
        if ! command -v socat &>/dev/null; then
            info "安装 socat..."
            apt-get update -qq && apt-get install -y -qq socat >/dev/null 2>&1 || \
            yum install -y -q socat >/dev/null 2>&1 || \
            error "socat 安装失败，请手动安装"
        fi

        # 创建 systemd 服务
        SERVICE_NAME="mcproxy-fwd-${LOCAL_PORT}"
        info "创建转发服务: $SERVICE_NAME"
        cat > "/etc/systemd/system/${SERVICE_NAME}.service" <<EOF
[Unit]
Description=MCProxy Port Forward ${LOCAL_PORT} -> ${TARGET_IP}:${TARGET_PORT}
After=network.target

[Service]
Type=simple
ExecStart=/usr/bin/socat TCP-LISTEN:${LOCAL_PORT},fork,reuseaddr TCP:${TARGET_IP}:${TARGET_PORT}
Restart=always
RestartSec=3
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

        systemctl daemon-reload
        systemctl enable "$SERVICE_NAME" >/dev/null 2>&1
        systemctl restart "$SERVICE_NAME"

        sleep 1
        if systemctl is-active --quiet "$SERVICE_NAME"; then
            info "转发启动成功"
        else
            error "转发启动失败，请检查: journalctl -u $SERVICE_NAME"
        fi

        # 防火墙
        if command -v ufw &>/dev/null; then
            ufw allow "$LOCAL_PORT"/tcp >/dev/null 2>&1 && info "UFW 已放行端口 $LOCAL_PORT"
        elif command -v firewall-cmd &>/dev/null; then
            firewall-cmd --permanent --add-port="$LOCAL_PORT"/tcp >/dev/null 2>&1
            firewall-cmd --reload >/dev/null 2>&1 && info "Firewalld 已放行端口 $LOCAL_PORT"
        fi

        # 获取本机 IP
        MY_IP=$(curl -s4 ip.sb 2>/dev/null || curl -s4 ifconfig.me 2>/dev/null || echo "YOUR_IP")

        echo ""
        echo -e "${CYAN}===== 转发配置完成 =====${NC}"
        echo ""
        echo -e "${GREEN}转发规则:${NC} ${MY_IP}:${LOCAL_PORT} -> ${TARGET_IP}:${TARGET_PORT}"
        echo -e "${GREEN}服务名称:${NC} ${SERVICE_NAME}"
        echo ""
        echo -e "${YELLOW}管理命令:${NC}"
        echo -e "  状态: ${CYAN}systemctl status $SERVICE_NAME${NC}"
        echo -e "  停止: ${CYAN}systemctl stop $SERVICE_NAME${NC}"
        echo -e "  删除: ${CYAN}systemctl stop $SERVICE_NAME && systemctl disable $SERVICE_NAME && rm /etc/systemd/system/${SERVICE_NAME}.service${NC}"
        echo ""

        # 如果目标端口是 MC 节点，生成客户端链接提示
        echo -e "${YELLOW}如果目标是 MCProxy 节点，客户端连接地址改为:${NC}"
        echo -e "${CYAN}${MY_IP}:${LOCAL_PORT}${NC}"
        echo ""
        exit 0
        ;;
    3) # 查看转发
        echo ""
        echo -e "${CYAN}===== 当前端口转发 =====${NC}"
        echo ""
        FOUND=0
        for svc in /etc/systemd/system/mcproxy-fwd-*.service; do
            [[ -f "$svc" ]] || continue
            FOUND=1
            SVC_NAME=$(basename "$svc" .service)
            DESC=$(grep "^Description=" "$svc" | cut -d= -f2-)
            STATUS=$(systemctl is-active "$SVC_NAME" 2>/dev/null || echo "inactive")
            if [[ "$STATUS" == "active" ]]; then
                echo -e "  ${GREEN}●${NC} $SVC_NAME - $DESC"
            else
                echo -e "  ${RED}●${NC} $SVC_NAME - $DESC ${RED}[$STATUS]${NC}"
            fi
        done
        if [[ $FOUND -eq 0 ]]; then
            echo -e "  ${YELLOW}没有配置任何端口转发${NC}"
        fi
        echo ""
        printf "%b" "${GREEN}是否删除某个转发？输入服务名或直接回车跳过${NC}: "
        read -r DEL_SVC
        if [[ -n "$DEL_SVC" ]]; then
            systemctl stop "$DEL_SVC" 2>/dev/null || true
            systemctl disable "$DEL_SVC" 2>/dev/null || true
            rm -f "/etc/systemd/system/${DEL_SVC}.service"
            systemctl daemon-reload
            info "已删除: $DEL_SVC"
        fi
        exit 0
        ;;
    4) # 卸载
        echo ""
        info "停止并卸载 Xray..."
        systemctl stop xray 2>/dev/null || true
        systemctl disable xray 2>/dev/null || true
        rm -f /usr/local/bin/xray /etc/systemd/system/xray.service
        rm -rf /etc/xray /var/log/xray

        # 也清理转发服务
        for svc in /etc/systemd/system/mcproxy-fwd-*.service; do
            [[ -f "$svc" ]] || continue
            SVC_NAME=$(basename "$svc" .service)
            systemctl stop "$SVC_NAME" 2>/dev/null || true
            systemctl disable "$SVC_NAME" 2>/dev/null || true
            rm -f "$svc"
        done
        systemctl daemon-reload
        info "卸载完成"
        exit 0
        ;;
    *)
        error "无效选择"
        ;;
esac

# ========== 以下是选项 1: 安装节点 ==========

# 检查架构
ARCH=$(uname -m)
case "$ARCH" in
    x86_64|amd64) ARCH_TAG="amd64" ;;
    aarch64|arm64) ARCH_TAG="arm64" ;;
    *) error "不支持的架构: $ARCH" ;;
esac

XRAY_BIN="/usr/local/bin/xray"
XRAY_DIR="/etc/xray"
XRAY_CONFIG="$XRAY_DIR/config.json"
XRAY_LOG_DIR="/var/log/xray"
DOWNLOAD_URL="https://get.coexa.cx/xray-mc-linux-${ARCH_TAG}"

echo ""
# 端口
printf "%b" "${GREEN}请输入监听端口 ${YELLOW}[默认: 25565]${NC}: "
read -r PORT
PORT=${PORT:-25565}

# 密码
printf "%b" "${GREEN}自动生成密码？${YELLOW}[Y/n]${NC}: "
read -r AUTO_PW
AUTO_PW=${AUTO_PW:-Y}
if [[ "$AUTO_PW" =~ ^[Yy]$ ]]; then
    if ! command -v openssl >/dev/null 2>&1; then
        error "未找到 openssl，请先安装 openssl 后重试"
    fi
    PASSWORD=$(openssl rand -base64 32)
    info "生成密码: $PASSWORD"
else
    printf "%b" "${GREEN}请输入 SS2022 密码 (base64)${NC}: "
    read -r PASSWORD
    [[ -z "$PASSWORD" ]] && error "密码不能为空"
fi

# 伪装域名
printf "%b" "${GREEN}Minecraft 伪装域名 ${YELLOW}[默认: play.hypixel.net]${NC}: "
read -r MC_HOST
MC_HOST=${MC_HOST:-play.hypixel.net}

# 加密方式
ENCRYPT="2022-blake3-aes-256-gcm"

# ========== 安装依赖 ==========
info "检查依赖..."
if ! command -v curl &>/dev/null; then
    apt-get update -qq && apt-get install -y -qq curl >/dev/null 2>&1 || \
    yum install -y -q curl >/dev/null 2>&1
fi

# ========== 停止旧服务 ==========
if systemctl is-active --quiet xray 2>/dev/null; then
    info "停止旧 xray 服务..."
    systemctl stop xray
fi
pkill -f "$XRAY_BIN" 2>/dev/null || true
sleep 1

# ========== 下载 Xray ==========
info "下载 Xray-MC (${ARCH_TAG})..."
curl -fSL -o "$XRAY_BIN" "$DOWNLOAD_URL" || error "下载失败，请检查网络"
chmod +x "$XRAY_BIN"

VERSION=$("$XRAY_BIN" version 2>/dev/null | head -1) || error "二进制文件无法执行"
info "已安装: $VERSION"

# ========== 创建目录 ==========
mkdir -p "$XRAY_DIR" "$XRAY_LOG_DIR"

# ========== 生成配置 ==========
info "生成配置文件..."
cat > "$XRAY_CONFIG" <<EOF
{
  "log": {
    "loglevel": "warning",
    "access": "$XRAY_LOG_DIR/access.log",
    "error": "$XRAY_LOG_DIR/error.log"
  },
  "inbounds": [
    {
      "port": $PORT,
      "listen": "0.0.0.0",
      "protocol": "shadowsocks",
      "settings": {
        "method": "$ENCRYPT",
        "password": "$PASSWORD",
        "network": "tcp"
      },
      "streamSettings": {
        "network": "minecraft",
        "minecraftSettings": {
          "serverAddress": "$MC_HOST",
          "serverPort": $PORT
        }
      }
    }
  ],
  "outbounds": [
    {
      "protocol": "freedom",
      "tag": "direct"
    }
  ]
}
EOF

# ========== 创建 systemd 服务 ==========
info "创建 systemd 服务..."
cat > /etc/systemd/system/xray.service <<EOF
[Unit]
Description=Xray-MC Service
After=network.target

[Service]
Type=simple
ExecStart=$XRAY_BIN run -c $XRAY_CONFIG
Restart=on-failure
RestartSec=3
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable xray >/dev/null 2>&1
systemctl start xray

sleep 1
if systemctl is-active --quiet xray; then
    info "Xray 服务启动成功"
else
    error "Xray 服务启动失败，请检查: journalctl -u xray"
fi

# ========== 防火墙 ==========
if command -v ufw &>/dev/null; then
    ufw allow "$PORT"/tcp >/dev/null 2>&1 && info "UFW 已放行端口 $PORT"
elif command -v firewall-cmd &>/dev/null; then
    firewall-cmd --permanent --add-port="$PORT"/tcp >/dev/null 2>&1
    firewall-cmd --reload >/dev/null 2>&1 && info "Firewalld 已放行端口 $PORT"
fi

# ========== 获取 IP ==========
SERVER_IP=$(curl -s4 ip.sb 2>/dev/null || curl -s4 ifconfig.me 2>/dev/null || echo "YOUR_SERVER_IP")

# ========== 生成链接 ==========
SS_LINK="ss://${ENCRYPT}:${PASSWORD}@${SERVER_IP}:${PORT}?plugin=minecraft%3Bserver%3D${MC_HOST}%3Bport%3D${PORT}#MCProxy-${SERVER_IP}"

echo ""
echo -e "${CYAN}========================================${NC}"
echo -e "${CYAN}  安装完成！${NC}"
echo -e "${CYAN}========================================${NC}"
echo ""
echo -e "${GREEN}服务器地址:${NC} $SERVER_IP"
echo -e "${GREEN}端口:${NC}       $PORT"
echo -e "${GREEN}加密方式:${NC}   $ENCRYPT"
echo -e "${GREEN}密码:${NC}       $PASSWORD"
echo -e "${GREEN}伪装类型:${NC}   minecraft transport"
echo -e "${GREEN}伪装域名:${NC}   $MC_HOST"
echo ""
echo -e "${YELLOW}SS 链接 (MCProxy 客户端专用):${NC}"
echo -e "${CYAN}$SS_LINK${NC}"
echo ""
echo -e "${YELLOW}管理命令:${NC}"
echo -e "  启动: ${CYAN}systemctl start xray${NC}"
echo -e "  停止: ${CYAN}systemctl stop xray${NC}"
echo -e "  重启: ${CYAN}systemctl restart xray${NC}"
echo -e "  状态: ${CYAN}systemctl status xray${NC}"
echo -e "  日志: ${CYAN}tail -f $XRAY_LOG_DIR/error.log${NC}"
echo -e "  配置: ${CYAN}$XRAY_CONFIG${NC}"
echo ""
echo -e "${GREEN}卸载: ${CYAN}重新运行脚本选择 4${NC}"
echo ""
