#!/bin/bash

# =============================================
# 判官标准版 - 宝塔一键部署脚本
# 适用于CentOS 7/8 或 Ubuntu 20.04+
# =============================================

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

# 配置变量
INSTALL_DIR="/www/wwwroot/panguan"
DB_NAME="panguan"
DB_USER="panguan"
DB_PASS="PG53719"
JAVA_PORT=5000
PHP_PORT=80

echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║    判官标准版 - 宝塔一键部署脚本         ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
echo ""

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}请使用root用户运行此脚本${NC}"
    exit 1
fi

# 检查宝塔面板
check_bt() {
    echo -e "${YELLOW}[1/8] 检查宝塔面板...${NC}"
    if [ -f "/www/server/panel/BT-Panel" ]; then
        echo -e "  ${GREEN}✓${NC} 宝塔面板已安装"
    else
        echo -e "  ${RED}✗${NC} 未检测到宝塔面板"
        echo -e "  ${CYAN}正在安装宝塔面板...${NC}"
        
        # 自动检测系统并安装
        if [ -f /etc/redhat-release ]; then
            yum install -y wget && wget -O install.sh https://download.bt.cn/install/install_6.0.sh && sh install.sh ed8484bec <<< "y"
        elif [ -f /etc/lsb-release ]; then
            wget -O install.sh https://download.bt.cn/install/install-ubuntu_6.0.sh && sudo bash install.sh ed8484bec <<< "y"
        fi
    fi
}

# 安装Java
install_java() {
    echo -e "${YELLOW}[2/8] 安装Java环境...${NC}"
    if command -v java &> /dev/null; then
        echo -e "  ${GREEN}✓${NC} Java已安装: $(java -version 2>&1 | head -1)"
    else
        echo -e "  ${CYAN}正在安装Java 8...${NC}"
        if [ -f /etc/redhat-release ]; then
            yum install -y java-1.8.0-openjdk java-1.8.0-openjdk-devel
        else
            apt-get update && apt-get install -y openjdk-8-jdk
        fi
        echo -e "  ${GREEN}✓${NC} Java安装完成"
    fi
}

# 安装MySQL
install_mysql() {
    echo -e "${YELLOW}[3/8] 检查MySQL...${NC}"
    if [ -f "/www/server/mysql/bin/mysql" ]; then
        echo -e "  ${GREEN}✓${NC} MySQL已安装"
    else
        echo -e "  ${YELLOW}!${NC} 请通过宝塔面板安装MySQL 5.7"
        echo -e "  ${CYAN}步骤: 宝塔面板 -> 软件商店 -> MySQL 5.7 -> 安装${NC}"
    fi
}

# 创建数据库
create_database() {
    echo -e "${YELLOW}[4/8] 创建数据库...${NC}"
    
    # 读取MySQL root密码
    local mysql_root_pass=$(cat /www/server/panel/default.pl 2>/dev/null | grep -oP 'mysql_root=\K[^&]+' || echo "")
    
    if [ -z "$mysql_root_pass" ]; then
        echo -n "  请输入MySQL root密码: "
        read -s mysql_root_pass
        echo ""
    fi
    
    # 创建数据库和用户
    mysql -uroot -p"$mysql_root_pass" << EOF
CREATE DATABASE IF NOT EXISTS $DB_NAME DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';
GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost';
FLUSH PRIVILEGES;
EOF
    
    if [ $? -eq 0 ]; then
        echo -e "  ${GREEN}✓${NC} 数据库创建成功"
        echo -e "    数据库名: ${CYAN}$DB_NAME${NC}"
        echo -e "    用户名: ${CYAN}$DB_USER${NC}"
        echo -e "    密码: ${CYAN}$DB_PASS${NC}"
    else
        echo -e "  ${YELLOW}!${NC} 数据库创建可能失败，请手动创建"
    fi
}

# 导入数据库
import_database() {
    echo -e "${YELLOW}[5/8] 导入数据库...${NC}"
    
    local sql_file="$INSTALL_DIR/QJB/AliQJB.sql"
    if [ -f "$sql_file" ]; then
        mysql -u$DB_USER -p$DB_PASS $DB_NAME < "$sql_file" 2>/dev/null
        if [ $? -eq 0 ]; then
            echo -e "  ${GREEN}✓${NC} 数据库导入成功 (200条规则)"
        else
            echo -e "  ${RED}✗${NC} 导入失败，请手动导入"
        fi
    else
        echo -e "  ${YELLOW}!${NC} SQL文件不存在"
    fi
}

# 配置Java程序
configure_java() {
    echo -e "${YELLOW}[6/8] 配置Java程序...${NC}"
    
    local config_file="$INSTALL_DIR/QJB/config/application.yml"
    if [ -f "$config_file" ]; then
        # 更新数据库配置
        sed -i "s|username:.*|username: $DB_USER|" "$config_file"
        sed -i "s|password:.*|password: $DB_PASS|" "$config_file"
        echo -e "  ${GREEN}✓${NC} 配置文件已更新"
    fi
    
    # 添加执行权限
    chmod +x "$INSTALL_DIR/QJB/"*.sh 2>/dev/null
    chmod +x "$INSTALL_DIR/QJB/jiagu/"*.sh 2>/dev/null
    chmod +x "$INSTALL_DIR/QJB/KeyTool/"*.sh 2>/dev/null
    
    echo -e "  ${GREEN}✓${NC} 脚本权限已设置"
}

# 启动Java程序
start_java() {
    echo -e "${YELLOW}[7/8] 启动Java程序...${NC}"
    
    cd "$INSTALL_DIR/QJB"
    
    # 停止现有进程
    if [ -f "AliPack.jar.pid" ]; then
        local old_pid=$(cat AliPack.jar.pid)
        kill $old_pid 2>/dev/null
        rm -f AliPack.jar.pid
    fi
    
    # 启动新进程
    nohup java -jar -Xms1024m -Xmx2048m AliPack.jar > /dev/null 2>&1 &
    echo $! > AliPack.jar.pid
    
    sleep 3
    
    if ps -p $(cat AliPack.jar.pid) > /dev/null 2>&1; then
        echo -e "  ${GREEN}✓${NC} Java程序启动成功"
        echo -e "    PID: ${CYAN}$(cat AliPack.jar.pid)${NC}"
        echo -e "    端口: ${CYAN}$JAVA_PORT${NC}"
    else
        echo -e "  ${RED}✗${NC} 启动失败，请检查日志"
    fi
}

# 显示完成信息
show_complete() {
    echo -e "${YELLOW}[8/8] 部署完成!${NC}"
    echo ""
    echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
    echo -e "${BLUE}║           部署完成 - 访问信息            ║${NC}"
    echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
    echo ""
    echo -e "${GREEN}可视化后台:${NC}"
    echo -e "  地址: ${CYAN}http://您的IP:$JAVA_PORT${NC}"
    echo -e "  账号: ${CYAN}admin${NC}"
    echo -e "  密码: ${CYAN}PG53719${NC}"
    echo ""
    echo -e "${GREEN}官网系统:${NC}"
    echo -e "  地址: ${CYAN}http://您的域名/website/${NC}"
    echo -e "  后台: ${CYAN}http://您的域名/website/admin.php${NC}"
    echo -e "  账号: ${CYAN}admin / PG53719${NC}"
    echo ""
    echo -e "${GREEN}目录列表:${NC}"
    echo -e "  地址: ${CYAN}http://您的域名/${NC}"
    echo -e "  后台: ${CYAN}http://您的域名/?c=admin${NC}"
    echo -e "  账号: ${CYAN}admin / PG53719${NC}"
    echo ""
    echo -e "${GREEN}管理入口:${NC}"
    echo -e "  地址: ${CYAN}http://您的域名/admin.html${NC}"
    echo ""
    echo -e "${YELLOW}提示:${NC}"
    echo -e "  1. 请在宝塔面板添加网站并绑定域名"
    echo -e "  2. 网站目录设置为: $INSTALL_DIR"
    echo -e "  3. 如需HTTPS，请在宝塔申请SSL证书"
    echo ""
}

# 主函数
main() {
    check_bt
    install_java
    install_mysql
    create_database
    import_database
    configure_java
    start_java
    show_complete
}

# 运行
main
