#!/bin/bash

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

# 全局变量
domain=""
db_root_password=""
db_user=""
db_password=""
os_type=""
os_version=""
web_root=""

# 显示菜单函数
show_menu() {
    clear
    echo -e "${GREEN}==================================${NC}"
    echo -e "${GREEN}        彩虹系统安装菜单${NC}"
    echo -e "${GREEN}==================================${NC}"
    echo -e "${BLUE}1. 全新安装彩虹系统${NC}"
    echo -e "${RED}0. 退出${NC}"
    echo -e "${GREEN}==================================${NC}"
    echo -n "请输入选项 [0-1]: "
}

# 检测操作系统
detect_os() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        os_type=$ID
        os_version=$VERSION_ID
        echo -e "${GREEN}检测到操作系统: $PRETTY_NAME${NC}"
        
        # 只支持Ubuntu和Debian
        if [[ "$os_type" != "ubuntu" && "$os_type" != "debian" ]]; then
            echo -e "${RED}错误: 此脚本只支持Ubuntu和Debian系统${NC}"
            exit 1
        fi
    else
        echo -e "${RED}无法检测操作系统类型${NC}"
        exit 1
    fi
}

# 检查是否以root用户运行
check_root() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}错误: 此脚本必须以root权限运行${NC}"
        exit 1
    fi
}

# 安装必要工具
install_tools() {
    echo -e "${GREEN}安装必要工具...${NC}"
    apt-get update
    apt-get install -y wget unzip curl expect
}

# 环境检测函数
check_environment() {
    echo -e "\n\n"
    echo -e "${MAGENTA}=======================================================${NC}"
    echo -e "${MAGENTA}                   环境检测中...                      ${NC}"
    echo -e "${MAGENTA}=======================================================${NC}"
    echo -e "\n"
    
    # 检测Nginx
    if command -v nginx &> /dev/null; then
        nginx_version=$(nginx -v 2>&1 | awk -F/ '{print $2}')
        echo -e "   Nginx: ${GREEN}已安装 (版本: $nginx_version)${NC}"
    else
        echo -e "   Nginx: ${RED}未安装${NC}"
    fi
    
    # 检测PHP
    if command -v php &> /dev/null; then
        php_version=$(php -v | head -n 1 | awk '{print $2}')
        echo -e "   PHP: ${GREEN}已安装 (版本: $php_version)${NC}"
    else
        echo -e "   PHP: ${RED}未安装${NC}"
    fi
    
    # 检测MySQL
    if command -v mysql &> /dev/null; then
        mysql_version=$(mysql --version | awk '{print $5}')
        echo -e "   MySQL: ${GREEN}已安装 (版本: $mysql_version)${NC}"
    else
        echo -e "   MySQL: ${RED}未安装${NC}"
    fi
    
    echo -e "\n"
    echo -e "${MAGENTA}                  PHP扩展检测                         ${NC}"
    echo -e "${MAGENTA}-------------------------------------------------------${NC}"
    
    # 检测PHP扩展
    php_extensions=("pdo" "pdo_mysql" "openssl" "fileinfo" "mbstring" "curl" "gd" "zip")
    
    for ext in "${php_extensions[@]}"; do
        if php -m | grep -i $ext &> /dev/null; then
            echo -e "   $ext: ${GREEN}已安装${NC}"
        else
            echo -e "   $ext: ${RED}未安装${NC}"
        fi
    done
    
    echo -e "\n"
    echo -e "${MAGENTA}=======================================================${NC}"
    echo -e "\n\n"
}

# 安装Nginx
install_nginx() {
    echo -e "${GREEN}开始安装Nginx...${NC}"
    
    apt-get install -y nginx
    
    # 启动Nginx并设置开机自启
    systemctl start nginx
    systemctl enable nginx
    
    # 配置防火墙
    if command -v ufw &> /dev/null; then
        ufw allow 'Nginx Full'
    fi
    
    echo -e "${GREEN}Nginx 安装完成!${NC}"
}

# 安装PHP
install_php() {
    echo -e "${GREEN}开始安装 PHP...${NC}"
    
    # 添加PHP仓库
    apt-get install -y software-properties-common
    add-apt-repository -y ppa:ondrej/php
    apt-get update
    apt-get install -y php8.0 php8.0-common php8.0-opcache php8.0-cli php8.0-gd php8.0-curl php8.0-mysql php8.0-json php8.0-zip php8.0-xml php8.0-mbstring php8.0-bcmath php8.0-fpm
    
    # 启动PHP-FPM并设置开机自启
    systemctl start php8.0-fpm
    systemctl enable php8.0-fpm
    
    echo -e "${GREEN}PHP 安装完成!${NC}"
}

# 安装MySQL 5.7
install_mysql() {
    echo -e "${GREEN}开始安装 MySQL 5.7...${NC}"
    
    # 下载并安装MySQL 5.7
    wget https://dev.mysql.com/get/mysql-apt-config_0.8.22-1_all.deb
    dpkg -i mysql-apt-config_0.8.22-1_all.deb
    
    # 更新包列表
    apt-get update
    
    # 安装MySQL 5.7
    apt-get install -y mysql-server=5.7.* mysql-client=5.7.*
    
    # 启动MySQL并设置开机自启
    systemctl start mysql
    systemctl enable mysql
    
    # 自动运行mysql_secure_installation
    echo -e "${GREEN}自动配置MySQL安全性...${NC}"
    
    # 使用expect自动应答mysql_secure_installation
    expect <<EOF
set timeout 10
spawn mysql_secure_installation
expect "Press y|Y for Yes, any other key for No:"
send "n\r"
expect "New password:"
send "$db_root_password\r"
expect "Re-enter new password:"
send "$db_root_password\r"
expect "Remove anonymous users? (Press y|Y for Yes, any other key for No) :"
send "y\r"
expect "Disallow root login remotely? (Press y|Y for Yes, any other key for No) :"
send "y\r"
expect "Remove test database and access to it? (Press y|Y for Yes, any other key for No) :"
send "y\r"
expect "Reload privilege tables now? (Press y|Y for Yes, any other key for No) :"
send "y\r"
expect eof
EOF
    
    # 创建数据库和用户
    echo -e "${GREEN}创建数据库和用户...${NC}"
    mysql -u root -p"$db_root_password" <<MYSQL_SCRIPT
CREATE DATABASE $db_user;
CREATE USER '$db_user'@'localhost' IDENTIFIED BY '$db_password';
GRANT ALL PRIVILEGES ON $db_user.* TO '$db_user'@'localhost';
FLUSH PRIVILEGES;
MYSQL_SCRIPT
    
    echo -e "${GREEN}MySQL 5.7 安装和配置完成!${NC}"
}

# 安装PHP扩展
install_php_extensions() {
    echo -e "${GREEN}安装所需的PHP扩展...${NC}"
    
    # 安装PHP扩展
    apt-get install -y php8.0-mysql php8.0-pdo php8.0-openssl php8.0-mbstring php8.0-curl php8.0-gd php8.0-zip
    
    # 重启PHP-FPM
    systemctl restart php8.0-fpm
    
    echo -e "${GREEN}PHP扩展安装完成!${NC}"
}

# 自动安装所需环境
auto_install_environment() {
    echo -e "${GREEN}开始自动安装所需环境...${NC}"
    
    # 检测并安装Nginx
    if ! command -v nginx &> /dev/null; then
        install_nginx
    else
        echo -e "${GREEN}Nginx 已安装，跳过安装${NC}"
    fi
    
    # 检测并安装PHP
    if ! command -v php &> /dev/null; then
        install_php
    else
        php_version=$(php -v | head -n 1 | awk '{print $2}')
        if [[ ! $php_version == 8.0* ]]; then
            echo -e "${YELLOW}检测到PHP版本为 $php_version，需要升级到8.0${NC}"
            install_php
        else
            echo -e "${GREEN}PHP 8.0 已安装，跳过安装${NC}"
        fi
    fi
    
    # 检测并安装MySQL
    if ! command -v mysql &> /dev/null; then
        install_mysql
    else
        mysql_version=$(mysql --version | awk '{print $5}')
        if [[ ! $mysql_version == 5.7* ]]; then
            echo -e "${YELLOW}检测到MySQL版本为 $mysql_version，需要安装5.7${NC}"
            install_mysql
        else
            echo -e "${GREEN}MySQL 5.7 已安装，跳过安装${NC}"
        fi
    fi
    
    # 安装PHP扩展
    install_php_extensions
    
    echo -e "${GREEN}环境安装完成!${NC}"
}

# 获取域名并验证
get_domain() {
    while true; do
        read -p "请输入要绑定的域名 (例如: example.com): " domain
        
        # 简单的域名格式验证
        if [[ $domain =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$ ]]; then
            echo -e "${GREEN}域名格式正确: $domain${NC}"
            break
        else
            echo -e "${RED}域名格式不正确，请重新输入${NC}"
        fi
    done
}

# 获取数据库配置信息
get_db_config() {
    # 获取MySQL root密码
    while true; do
        read -s -p "请设置MySQL root密码: " db_root_password
        echo
        read -s -p "请再次确认MySQL root密码: " db_root_password_confirm
        echo
        
        if [ "$db_root_password" = "$db_root_password_confirm" ]; then
            break
        else
            echo -e "${RED}两次输入的密码不一致，请重新输入${NC}"
        fi
    done
    
    # 获取数据库用户名
    read -p "请输入数据库用户名: " db_user
    
    # 获取数据库用户密码
    while true; do
        read -s -p "请设置数据库用户密码: " db_password
        echo
        read -s -p "请再次确认数据库用户密码: " db_password_confirm
        echo
        
        if [ "$db_password" = "$db_password_confirm" ]; then
            break
        else
            echo -e "${RED}两次输入的密码不一致，请重新输入${NC}"
        fi
    done
    
    echo -e "${GREEN}数据库配置信息已保存${NC}"
}

# 创建网站目录
create_web_directory() {
    local domain=$1
    web_root="/var/www/$domain"
    
    echo -e "${GREEN}创建网站目录: $web_root${NC}"
    mkdir -p $web_root
    chown -R www-data:www-data $web_root
    chmod -R 755 $web_root
    
    # 跳过创建默认首页
    echo -e "${YELLOW}跳过创建默认首页${NC}"
}

# 配置Nginx虚拟主机
configure_nginx() {
    local domain=$1
    local web_root="/var/www/$domain"
    
    echo -e "${GREEN}配置Nginx虚拟主机...${NC}"
    
    # 创建Nginx配置文件
    cat > /etc/nginx/sites-available/$domain << EOF
server {
    listen 80;
    server_name $domain www.$domain;
    root $web_root;
    index index.html index.php;
    
    access_log /var/log/nginx/${domain}_access.log;
    error_log /var/log/nginx/${domain}_error.log;
    
    location / {
        try_files \$uri \$uri/ /index.php?\$args;
    }
    
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
    }
    
    location ~ /\.ht {
        deny all;
    }
}
EOF
    
    # 启用站点
    ln -sf /etc/nginx/sites-available/$domain /etc/nginx/sites-enabled/
    
    # 测试Nginx配置
    nginx -t
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}Nginx配置测试成功${NC}"
        systemctl reload nginx
    else
        echo -e "${RED}Nginx配置测试失败，请检查配置${NC}"
        exit 1
    fi
}

# 下载彩虹系统
download_rainbow_system() {
    local web_root=$1
    
    echo -e "${GREEN}开始下载彩虹系统...${NC}"
    
    # 这里替换为实际的彩虹系统下载URL
    # 示例URL，请根据实际情况修改
    rainbow_url="https://github.com/your-rainbow-system/release/archive/master.zip"
    
    # 下载到临时目录
    cd /tmp
    wget -O rainbow-system.zip $rainbow_url
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}下载成功${NC}"
        # 解压到网站目录
        unzip -o rainbow-system.zip -d $web_root/
        
        # 设置权限
        chown -R www-data:www-data $web_root
        chmod -R 755 $web_root
        
        echo -e "${GREEN}彩虹系统已安装到 $web_root${NC}"
    else
        echo -e "${RED}下载失败，请检查网络连接和URL${NC}"
        exit 1
    fi
}

# 显示安装完成信息
show_completion() {
    local domain=$1
    
    echo -e "${GREEN}==================================${NC}"
    echo -e "${GREEN}       安装完成!${NC}"
    echo -e "${GREEN}==================================${NC}"
    echo -e "前台地址: ${YELLOW}http://$domain${NC}"
    echo -e "后台地址: ${YELLOW}http://$domain/admin${NC}"
    echo -e "默认账号: ${YELLOW}admin${NC}"
    echo -e "默认密码: ${YELLOW}123456${NC}"
    echo -e "数据库名: ${YELLOW}$db_user${NC}"
    echo -e "数据库用户: ${YELLOW}$db_user${NC}"
    echo -e "数据库密码: ${YELLOW}$db_password${NC}"
    echo -e "${GREEN}==================================${NC}"
    echo -e "${YELLOW}请注意: 首次登录后请立即修改默认密码!${NC}"
    echo -e "${GREEN}==================================${NC}"
    
    read -n 1 -s -r -p "按任意键返回菜单..."
}

# 全新安装彩虹系统
install_rainbow() {
    echo -e "${GREEN}开始全新安装彩虹系统...${NC}"
    
    # 获取域名
    get_domain
    
    # 获取数据库配置信息
    get_db_config
    
    # 环境检测
    check_environment
    
    # 询问是否自动安装所需环境
    read -p "是否自动安装/更新所需环境? (y/N): " install_env
    if [ "$install_env" = "y" ] || [ "$install_env" = "Y" ]; then
        auto_install_environment
    else
        echo -e "${YELLOW}跳过环境安装，请确保所需环境已正确安装${NC}"
    fi
    
    # 再次检测环境
    echo -e "${GREEN}最终环境检测:${NC}"
    check_environment
    
    # 创建网站目录
    create_web_directory $domain
    
    # 配置Nginx
    configure_nginx $domain
    
    # 下载彩虹系统
    download_rainbow_system "/var/www/$domain"
    
    # 显示完成信息
    show_completion $domain
}

# 主函数
main() {
    check_root
    detect_os
    install_tools
    
    while true; do
        show_menu
        read choice
        case $choice in
            1) install_rainbow ;;
            0)
                echo -e "${GREEN}退出脚本，再见！${NC}"
                exit 0
                ;;
            *)
                echo -e "${RED}无效选项，请重新输入${NC}"
                sleep 2
                ;;
        esac
    done
}

# 执行主函数
main