#!/bin/bash

red='\033[0;31m'
green='\033[0;32m'
blue='\033[0;34m'
yellow='\033[0;33m'
plain='\033[0m'

cur_dir=$(pwd)
show_ip_service_lists=("https://api.ipify.org" "https://4.ident.me")
local_tar_path="/www/wwwroot/soft.fengchensw.com/x-ui.tar.gz"
remote_tar_url="https://soft.fengchensw.com/x-ui.tar.gz"

# 检查root权限
[[ $EUID -ne 0 ]] && echo -e "${red}致命错误: ${plain} 请使用root权限运行此脚本 \n " && exit 1

# 检查操作系统
if [[ -f /etc/os-release ]]; then
    source /etc/os-release
    release=$ID
elif [[ -f /usr/lib/os-release ]]; then
    source /usr/lib/os-release
    release=$ID
else
    echo "无法检测系统类型，请联系作者！" >&2
    exit 1
fi
echo "操作系统版本: $release"

arch() {
    case "$(uname -m)" in
    x86_64 | x64 | amd64) echo 'amd64' ;;
    i*86 | x86) echo '386' ;;
    armv8* | armv8 | arm64 | aarch64) echo 'arm64' ;;
    armv7* | armv7 | arm) echo 'armv7' ;;
    armv6* | armv6) echo 'armv6' ;;
    armv5* | armv5) echo 'armv5' ;;
    s390x) echo 's390x' ;;
    *) echo -e "${green}不支持的CPU架构! ${plain}" && rm -f install.sh && exit 1 ;;
    esac
}

echo "系统架构: $(arch)"

install_base() {
    case "${release}" in
    ubuntu | debian | armbian)
        apt-get update && apt-get install -y -q wget curl tar tzdata
        ;;
    centos | rhel | almalinux | rocky | ol)
        yum -y update && yum install -y -q wget curl tar tzdata
        ;;
    fedora | amzn | virtuozzo)
        dnf -y update && dnf install -y -q wget curl tar tzdata
        ;;
    arch | manjaro | parch)
        pacman -Syu && pacman -Syu --noconfirm wget curl tar tzdata
        ;;
    opensuse-tumbleweed)
        zypper refresh && zypper -q install -y wget curl tar timezone
        ;;
    *)
        apt-get update && apt-get install -y -q wget curl tar tzdata
        ;;
    esac
}

gen_random_string() {
    local length="$1"
    local random_string=$(LC_ALL=C tr -dc 'a-zA-Z0-9' </dev/urandom | fold -w "$length" | head -n 1)
    echo "$random_string"
}

config_after_install() {
    local existing_hasDefaultCredential=$(/usr/local/x-ui/x-ui setting -show true | grep -Eo 'hasDefaultCredential: .+' | awk '{print $2}')
    local existing_webBasePath=$(/usr/local/x-ui/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
    local existing_port=$(/usr/local/x-ui/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')

    for ip_service_addr in "${show_ip_service_lists[@]}"; do
        local server_ip=$(curl -s --max-time 3 ${ip_service_addr} 2>/dev/null)
        if [ -n "${server_ip}" ]; then
            break
        fi
    done

    if [[ ${#existing_webBasePath} -lt 4 ]]; then
        if [[ "$existing_hasDefaultCredential" == "true" ]]; then
            local config_webBasePath=$(gen_random_string 18)
            local config_username=$(gen_random_string 10)
            local config_password=$(gen_random_string 10)

                local config_port=$(shuf -i 1024-62000 -n 1)

            /usr/local/x-ui/x-ui setting -username "${config_username}" -password "${config_password}" -port "${config_port}" -webBasePath "${config_webBasePath}"
            echo -e "请记录好此信息 如有忘记可输入 x-ui settings 重新显示此信息"
            echo -e "###############################################"
            echo -e "${green}用户名: ${config_username}${plain}"
            echo -e "${green}密码: ${config_password}${plain}"
            echo -e "${green}端口: ${config_port}${plain}"
            echo -e "${green}网页路径: ${config_webBasePath}${plain}"
            echo -e "${green}访问地址: http://${server_ip}:${config_port}/${config_webBasePath}${plain}"
            echo -e "###############################################"
        else
            local config_webBasePath=$(gen_random_string 18)
            echo -e "${yellow}网页路径缺失或过短，正在生成新的路径...${plain}"
            /usr/local/x-ui/x-ui setting -webBasePath "${config_webBasePath}"
            echo -e "${green}新网页路径: ${config_webBasePath}${plain}"
            echo -e "${green}访问地址: http://${server_ip}:${existing_port}/${config_webBasePath}${plain}"
        fi
    else
        if [[ "$existing_hasDefaultCredential" == "true" ]]; then
            local config_username=$(gen_random_string 10)
            local config_password=$(gen_random_string 10)

            echo -e "${yellow}检测到默认凭证，需要进行安全更新...${plain}"
            /usr/local/x-ui/x-ui setting -username "${config_username}" -password "${config_password}"
            echo -e "已生成新的随机登录凭证:"
            echo -e "###############################################"
            echo -e "${green}用户名: ${config_username}${plain}"
            echo -e "${green}密码: ${config_password}${plain}"
            echo -e "###############################################"
        else
            echo -e "${green}用户名、密码和网页路径已正确设置，退出...${plain}"
        fi
    fi

    /usr/local/x-ui/x-ui migrate
}

download_xui_package() {
    echo -e "${blue}检查本地安装包...${plain}"
    
    # 首先检查本地路径
    if [[ -f "$local_tar_path" ]]; then
        echo -e "${green}找到本地安装包: $local_tar_path ${plain}"
        cp "$local_tar_path" /tmp/x-ui.tar.gz
        return 0
    fi
    
    echo -e "${yellow}本地安装包不存在，尝试从网络下载...${plain}"
    echo -e "${blue}下载地址: $remote_tar_url ${plain}"
    
    # 尝试使用wget下载
    if command -v wget &> /dev/null; then
        if wget --timeout=30 --tries=3 -O /tmp/x-ui.tar.gz "$remote_tar_url"; then
            echo -e "${green}下载成功 ${plain}"
            return 0
        fi
    fi
    
    # 如果wget失败，尝试使用curl下载
    if command -v curl &> /dev/null; then
        if curl --connect-timeout 30 --retry 3 -o /tmp/x-ui.tar.gz -L "$remote_tar_url"; then
            echo -e "${green}下载成功 ${plain}"
            return 0
        fi
    fi
    
    echo -e "${red}错误: 无法从网络下载安装包 ${plain}"
    return 1
}

install_x-ui() {
    cd /usr/local/

    # 停止x-ui服务
    if systemctl is-active --quiet x-ui; then
        systemctl stop x-ui
    fi

    # 清理旧的x-ui资源
    if [[ -e /usr/local/x-ui ]]; then
        echo -e "${yellow}清理旧的x-ui资源...${plain}"
        rm -rf /usr/local/x-ui
    fi

    # 下载安装包
    if ! download_xui_package; then
        echo -e "${red}获取x-ui安装包失败 ${plain}"
        exit 1
    fi

    # 创建x-ui目录
    mkdir -p /usr/local/x-ui
    cd /usr/local/x-ui

    # 解压安装包到当前目录
    echo -e "开始解压x-ui..."
    tar zxvf /tmp/x-ui.tar.gz -C /usr/local/x-ui/
    if [[ $? -ne 0 ]]; then
        echo -e "${red}解压x-ui失败 ${plain}"
        rm -f /tmp/x-ui.tar.gz
        exit 1
    fi

    # 清理临时文件
    rm -f /tmp/x-ui.tar.gz

    # 检查必要的文件是否存在
    if [[ ! -f x-ui.sh ]]; then
        echo -e "${red}解压后未找到x-ui.sh管理脚本 ${plain}"
        ls -la /usr/local/x-ui/
        exit 1
    fi

    if [[ ! -f x-ui ]]; then
        echo -e "${red}解压后未找到x-ui可执行文件 ${plain}"
        ls -la /usr/local/x-ui/
        exit 1
    fi

    chmod +x x-ui
    chmod +x x-ui.sh

    # 检查系统架构并重命名文件
    if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
        if [[ -f bin/xray-linux-$(arch) ]]; then
            mv bin/xray-linux-$(arch) bin/xray-linux-arm
            chmod +x bin/xray-linux-arm
        fi
    fi
    
    if [[ -f bin/xray-linux-$(arch) ]]; then
        chmod +x bin/xray-linux-$(arch)
    fi

    # 使用解压后的x-ui.sh作为管理脚本
    cp -f x-ui.sh /usr/bin/x-ui
    chmod +x /usr/bin/x-ui

    config_after_install

    if [[ -f x-ui.service ]]; then
        cp -f x-ui.service /etc/systemd/system/
        systemctl daemon-reload
        systemctl enable x-ui
        systemctl start x-ui
    else
        echo -e "${yellow}警告: 未找到x-ui.service文件，服务可能需要手动配置 ${plain}"
    fi
    
    echo -e "${green}x-ui 安装完成 ${plain}"
    echo -e ""
    echo -e "┌────────────────────────────────────────────────┐
│  ${blue}x-ui 控制菜单使用说明:${plain}                        │
│                                                │
│  ${blue}x-ui${plain}              - 管理脚本                  │
│  ${blue}x-ui start${plain}        - 启动                      │
│  ${blue}x-ui stop${plain}         - 停止                      │
│  ${blue}x-ui restart${plain}      - 重启                      │
│  ${blue}x-ui status${plain}       - 查看状态                  │
│  ${blue}x-ui settings${plain}     - 查看设置                  │
│  ${blue}x-ui enable${plain}       - 设置开机自启              │
│  ${blue}x-ui disable${plain}      - 取消开机自启              │
│  ${blue}x-ui log${plain}          - 查看日志                  │
│  ${blue}x-ui banlog${plain}       - 查看封禁日志              │
│  ${blue}x-ui update${plain}       - 更新                      │
│  ${blue}x-ui legacy${plain}       - 旧版                      │
│  ${blue}x-ui install${plain}      - 安装                      │
│  ${blue}x-ui uninstall${plain}    - 卸载                      │
└────────────────────────────────────────────────┘"
}

install_base
install_x-ui
x-ui