#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # 无颜色

# 显示彩色消息
show_msg() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

show_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

show_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# 安装必要工具
install_tools() {
    show_msg "检查并安装必要工具..."
    
    # 检测包管理器
    if command -v apt-get &> /dev/null; then
        # Debian/Ubuntu
        PKG_MANAGER="apt-get"
        UPDATE_CMD="apt-get update"
        INSTALL_CMD="apt-get install -y"
    elif command -v yum &> /dev/null; then
        # CentOS/RHEL
        PKG_MANAGER="yum"
        UPDATE_CMD="yum check-update"
        INSTALL_CMD="yum install -y"
    elif command -v dnf &> /dev/null; then
        # Fedora
        PKG_MANAGER="dnf"
        UPDATE_CMD="dnf check-update"
        INSTALL_CMD="dnf install -y"
    else
        show_error "无法识别的包管理器，请手动安装 screen, wget 和 unzip"
        exit 1
    fi
    
    # 更新包列表
    show_msg "更新包列表..."
    eval "sudo $UPDATE_CMD"
    
    # 检查并安装screen
    if ! command -v screen &> /dev/null; then
        show_msg "安装 screen..."
        eval "sudo $INSTALL_CMD screen"
    else
        show_msg "screen 已安装"
    fi
    
    # 检查并安装wget
    if ! command -v wget &> /dev/null; then
        show_msg "安装 wget..."
        eval "sudo $INSTALL_CMD wget"
    else
        show_msg "wget 已安装"
    fi
    
    # 检查并安装unzip
    if ! command -v unzip &> /dev/null; then
        show_msg "安装 unzip..."
        eval "sudo $INSTALL_CMD unzip"
    else
        show_msg "unzip 已安装"
    fi
}

# 生成随机端口
generate_random_port() {
    echo $((RANDOM % 10000 + 20000))
}

# 安装服务器
install_server() {
    show_msg "开始安装 Minecraft PocketEdition 0.14 服务器..."
    
    # 创建mc目录
    mkdir -p /root/mc
    cd /root/mc
    
    # 下载服务器文件
    show_msg "正在下载服务器文件..."
    wget -O server.zip "https://cloud.999845.xyz/down.php/3b83ef905f0dc6f14958864add01e430.zip"
    
    if [ $? -ne 0 ]; then
        show_error "下载服务器文件失败"
        exit 1
    fi
    
    # 解压文件
    show_msg "正在解压文件..."
    unzip -o server.zip
    rm -f server.zip
    
    # 查找启动脚本文件
    START_SCRIPT=$(find . -name "*.sh" | grep -E "(启动|start)" | head -n 1)
    
    if [ -z "$START_SCRIPT" ]; then
        show_error "未找到启动脚本"
        exit 1
    fi
    
    # 授予权限
    show_msg "设置文件权限..."
    chmod 777 start.sh frpc "$START_SCRIPT"
    chmod -R 777 bin/
    
    # 配置服务器
    show_msg "开始配置服务器..."
    
    # 获取服务器标题
    echo -n "请输入服务器标题: "
    read server_motd </dev/tty
    # 转义特殊字符
    server_motd=$(echo "$server_motd" | sed 's/\\/\\\\/g')
    
    # 生成随机端口
    random_port=$(generate_random_port)
    show_msg "使用随机端口: $random_port"
    
    # 更新server.properties
    if [ -f "server.properties" ]; then
        sed -i "s/^motd=.*/motd=$server_motd/" server.properties
        sed -i "s/^server-port=.*/server-port=$random_port/" server.properties
        # 修复hardcore配置错误
        sed -i "s/^hardcore=oon/hardcore=on/" server.properties
    else
        show_warning "server.properties 文件不存在，将创建新配置"
        cat > server.properties << EOF
#Properties Config file
motd=$server_motd
server-port=$random_port
white-list=off
announce-player-achievements=on
spawn-protection=1
max-players=10
allow-flight=on
spawn-animals=on
spawn-mobs=on
gamemode=0
force-gamemode=off
hardcore=on
pvp=on
difficulty=1
generator-settings=
level-name=world
level-seed=
level-type=DEFAULT
enable-query=on
enable-rcon=off
rcon.password=cczzvDEXaP
auto-save=on
EOF
    fi
    
    # 更新frpc.toml
    if [ -f "frpc.toml" ]; then
        sed -i "s/^localPort = .*/localPort = $random_port/" frpc.toml
        sed -i "s/^remotePort = .*/remotePort = $random_port/" frpc.toml
    else
        show_warning "frpc.toml 文件不存在，将创建新配置"
        cat > frpc.toml << EOF
serverAddr = "121.62.17.181"
serverPort = 65502

[[proxies]]
name = "minecraft_server"
type = "udp"
localIP = "127.0.0.1"
localPort = $random_port
remotePort = $random_port
EOF
    fi
    
    show_msg "服务器安装和配置完成!"
    show_msg "进服地址: 121.62.17.181:$random_port"
    
    # 询问是否立即启动服务器
    echo -n "是否立即启动服务器? (y/n): "
    read start_now </dev/tty
    if [ "$start_now" = "y" ] || [ "$start_now" = "Y" ]; then
        start_server
    fi
}

# 启动服务器
start_server() {
    show_msg "启动 Minecraft 服务器..."
    cd /root/mc
    
    # 查找启动脚本文件
    START_SCRIPT=$(find . -name "*.sh" | grep -E "(启动|start)" | head -n 1)
    
    # 检查服务器是否已安装
    if [ -z "$START_SCRIPT" ]; then
        show_error "未找到启动脚本，请先运行安装选项"
        exit 1
    fi
    
    # 使用screen启动服务器
    screen -S minecraft -d -m bash -c "cd /root/mc && ./\"$START_SCRIPT\""
    show_msg "服务器已在screen会话中启动，会话名称: minecraft"
    show_msg "使用 'screen -r minecraft' 查看服务器控制台"
    show_msg "使用 Ctrl+A then D 退出screen会话而不停止服务器"
}

# 主菜单
main_menu() {
    echo -e "${BLUE}================================${NC}"
    echo -e "${BLUE}    ioip PE 一键炸飞graphic脚本    ${NC}"
    echo -e "${BLUE}================================${NC}"
    echo "1. 安装服务器"
    echo "2. 启动服务器"
    echo "3. 退出"
    echo -e "${BLUE}================================${NC}"
    
    echo -n "请选择操作 [1-3]: "
    read choice </dev/tty
    
    case $choice in
        1)
            install_tools
            install_server
            ;;
        2)
            install_tools
            start_server
            ;;
        3)
            show_msg "再见!"
            exit 0
            ;;
        *)
            show_error "无效选择"
            exit 1
            ;;
    esac
}

# 显示欢迎信息
show_msg "Minecraft PocketEdition 0.14 一键开服脚本"

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    show_warning "建议使用root用户运行此脚本以获得最佳体验"
    echo -n "是否继续? (y/n): "
    read continue_as_user </dev/tty
    if [ "$continue_as_user" != "y" ] && [ "$continue_as_user" != "Y" ]; then
        exit 1
    fi
fi

# 启动主菜单
main_menu