#!/bin/bash
#
#       XfPanel Installer Script v1.0.0
#   GitHub: https://github.com/XfPanel/XfPanel
#   Author: HerobrineXiaofeng
#
#   This script installs XfPanel to your system.
#   Usage:
#
#   	curl -fsSL https://get.xfpanel.com | bash
#   	or
#   	wget -qO- https://get.xfpanel.com | bash
#
# ===================== 变量 =====================
GREEN='\033[0;32m'
C='\033[1;36m'
W='\033[1;37m'
RED='\033[0;31m'
CBL='\033[38;2;88;166;255m'
NC='\033[0m'
SERIES=$(curl -s https://xfpanel.com/package/latest)
VERSION=$(curl -s https://xfpanel.com/package/${SERIES}/Stable/latest)
PANEL_DIR="/www/xfpanel"
CONF_DIR="${PANEL_DIR}/config"
LANG_FILE="${CONF_DIR}/lang.conf"
CHANNEL="stable"

# ==================== 多语言核心函数 ====================
first_lang_choose() {
    [ -d "${CONF_DIR}" ] || mkdir -p -m 700 "${CONF_DIR}"
    while true; do
        echo -e "${CBL}Select a language:${NC}"
        echo "1) 简体中文"
        echo "2) 繁體中文"
        echo "3) English"
        read -rp "Your choice: " sel < /dev/tty   # ← 关键修复
        case "$sel" in
            1) echo "zh_cn" > "${LANG_FILE}" && break ;;
            2) echo "zh_hk" > "${LANG_FILE}" && break ;;
            3) echo "en"    > "${LANG_FILE}" && break ;;
            *) echo -e "${RED}Invalid input, please try again.${NC}" ;;
        esac
    done
}

init_lang() {
    if [ ! -f "${LANG_FILE}" ]; then
        first_lang_choose   # 目录创建已移入 first_lang_choose
    fi
    CURRENT_LANG=$(cat "${LANG_FILE}" 2>/dev/null)
    export CURRENT_LANG="${CURRENT_LANG:-zh_cn}"
}

lang_text() {
    local key="$1"
    case "${CURRENT_LANG}" in
        zh_cn)
            case "$key" in
                install_confirm) echo "是否继续安装 XfPanel？(y/N) " ;;
                select_the_source) echo "请选择安装包源" ;;
            esac
        ;;
        zh_hk)
            case "$key" in
                install_confirm) echo "是否繼續安裝 XfPanel？(y/N) " ;;
                select_the_source) echo "請選擇安裝包源" ;;
            esac
        ;;
        en)
            case "$key" in
                install_confirm) echo "Continue to install XfPanel? (y/N) " ;;
                select_the_source) echo "Please select the source of the installation package" ;;
            esac
        ;;
    esac
}

parse_args() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --stable)
                CHANNEL="Stable"
                shift
                ;;
            --260520lts)
                CHANNEL="260520lts"
                VERSION=$(curl -s https://xfpanel.com/package/${SERIES}/Stable/latest-lts)
                shift
                ;;
            --beta)
                CHANNEL="beta"
                VERSION=$(curl -s https://xfpanel.com/package/${SERIES}/beta/latest)
                shift
                ;;
            --h)
                echo -e "${CBL}可用安装命令：${NC}"
                echo "  正式版：curl -fsSL https://get.xfpanel.com | bash"
                echo "  LTS版： curl -fsSL https://get.xfpanel.com | bash -s -- --260520lts"
                echo "  测试版：curl -fsSL https://get.xfpanel.com | bash -s -- --beta"
                exit 0
                ;;
            *)
                echo -e "${CBL}未知参数: $1${NC}"
                echo "使用 -h 查看帮助"
                exit 1
                ;;
        esac
    done
}

init_lang
# 修复：逻辑顺序 先解析参数
parse_args "$@"

# 获取系统内核名称
OS_TYPE=$(uname -s)
case $OS_TYPE in
    Darwin)
        echo "当前系统为 macOS，无法安装XfPanel，请使用 Linux 系统(服务器版本如 Debian/Centos)安装XfPanel"
        exit 1
        ;;
    MINGW*|MSYS*|CYGWIN*)
        echo "❌ 检测到当前系统为 Windows（含Server服务器版），本脚本不支持安装！"
        exit 1
        ;;
esac

# 架构检测
osCheck=$(uname -a)
if [[ $osCheck =~ 'x86_64' ]]; then
    architecture="amd64"
elif [[ $osCheck =~ 'arm64' ]] || [[ $osCheck =~ 'aarch64' ]]; then
    architecture="arm64"
#elif [[ $osCheck =~ 'armv7l' ]]; then
#    architecture="armv7"
#elif [[ $osCheck =~ 'ppc64le' ]]; then
#    architecture="ppc64le"
#elif [[ $osCheck =~ 's390x' ]]; then
#    architecture="s390x"
#elif [[ $osCheck =~ 'riscv64' ]]; then
#    architecture="riscv64"
else
    echo "当前系统架构暂不支持，请参考官方文档选择受支持的系统与架构。"
    exit 1
fi

if [[ "x${VERSION}" == "x" ]]; then
    echo "获取最新版本失败（模式：${CHANNEL}），请稍后重试。"
    exit 1
fi

PACKAGE_FILE_NAME="xfpanel-${VERSION}-linux-${architecture}.tar.gz"
PACKAGE_DOWNLOAD_URL="https://xfpanel.com/package/${SERIES}/${CHANNEL}/${VERSION}/${PACKAGE_FILE_NAME}"

# 标题输出（现在变量都已定义，不会乱码）
clear
cat << EOF
██╗  ██╗███████╗██████╗  █████╗ ███╗   ██╗███████╗██╗     
╚██╗██╔╝██╔════╝██╔══██╗██╔══██╗████╗  ██║██╔════╝██║     
 ╚███╔╝ █████╗  ██████╔╝███████║██╔██╗ ██║█████╗  ██║     
 ██╔██╗ ██╔══╝  ██╔═══╝ ██╔══██║██║╚██╗██║██╔══╝  ██║     
██╔╝ ██╗██║     ██║     ██║  ██║██║ ╚████║███████╗███████╗
╚═╝  ╚═╝╚═╝     ╚═╝     ╚═╝  ╚═╝╚═╝  ╚═══╝╚══════╝╚══════╝
EOF
echo "         XfPanel Installer ${VERSION}  ${CHANNEL} Channel         "
# 强制时间为标准格式，禁止中文本地化
echo -e "${CBL}[XfPanel $(date +"%Y-%m-%d %H:%M:%S") install Log]: ======================= 开始安装 =======================${NC}"
# 必须 root
if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}[XfPanel $(date +"%Y-%m-%d %H:%M:%S") install Log]: 请以 root 用户身份运行此脚本。${NC}"
  exit 1
fi
# 安装前二次确认
read -rp "$(lang_text install_confirm)" CONFIRM_INSTALL  < /dev/tty
if [[ ! "${CONFIRM_INSTALL,,}" =~ ^y$ ]]; then
    echo -e "${RED}已取消安装${NC}"
    exit 0
fi
echo -e "${CBL}[XfPanel $(date +"%Y-%m-%d %H:%M:%S") install Log]: 确认安装${NC}"
# 循环选择，直到输入正确
while true; do
echo "$(lang_text select_the_source)"
echo "1) 官网"
echo "2) Github(暂未添加文件)"
echo "3) Gitee(暂未添加文件)"

read -p "请输入选项(1/2/3): " opt </dev/tty
# 原生去首尾空格，不依赖xargs
opt="${opt#"${opt%%[![:space:]]*}"}"
opt="${opt%"${opt##*[![:space:]]}"}"

case $opt in
    1)
        PACKAGE_DOWNLOAD_URL="https://xfpanel.com/package/${SERIES}/${CHANNEL}/${VERSION}/${PACKAGE_FILE_NAME}"
        INSTALLATION_SOURCE="Official"
        break
        ;;
    2)
        PACKAGE_DOWNLOAD_URL="https://raw.githubusercontent.com/XfPanel/XfPanel/main/package/${SERIES}/${CHANNEL}/${VERSION}/${PACKAGE_FILE_NAME}"
        INSTALLATION_SOURCE="Github"
        break
        ;;
    3)
        PACKAGE_DOWNLOAD_URL="https://gitee.com/XfPanel/XfPanel/raw/main/package/${SERIES}/${CHANNEL}/${VERSION}/${PACKAGE_FILE_NAME}"
        INSTALLATION_SOURCE="Gitee"
        break
        ;;
    *)
        echo -e "${RED}输入无效，请重新选择 1/2/3${NC}"
        ;;
esac
done
echo -e "${CBL}[XfPanel $(date +"%Y-%m-%d %H:%M:%S") install Log]: 已选择安装源: ${INSTALLATION_SOURCE}${NC}" 
echo -e "${CBL}[XfPanel $(date +"%Y-%m-%d %H:%M:%S") install Log]: 下载地址: ${PACKAGE_DOWNLOAD_URL}${NC}"
#echo -e "${CBL}[XfPanel $(date +"%Y-%m-%d %H:%M:%S") install Log]: 下载中...${NC}"
#curl -LOk ${PACKAGE_DOWNLOAD_URL}
echo -e "${CBL}[XfPanel $(date +"%Y-%m-%d %H:%M:%S") install Log]: 下载文件完成，开始解压到${PANEL_DIR}(暂未创建压缩包)${NC}"
rm -rf ${PANEL_DIR} && mkdir -p ${PANEL_DIR} #&& tar -zxvf ${PACKAGE_FILE_NAME} -C /www/xfpanel/
