#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
LANG=en_US.UTF-8

if [ $(whoami) != "root" ]; then
    echo "xp面板安装命令需要root权限执行"
    exit 1
fi

is64bit=$(getconf LONG_BIT)
if [ "${is64bit}" != '64' ]; then
    echo "xp面板仅支持64位系统安装"
    exit 1
fi

arch_check=$(uname -m)
if [ "${arch_check}" != "x86_64" ] && [ "${arch_check}" != "amd64" ]; then
    echo "xp面板仅支持x86_64或者amd64架构CPU的系统安装"
    exit 1
fi

if grep -qi 'centos' /etc/os-release; then
    # Centos6不支持安装
    centos6_check=$(cat /etc/redhat-release | grep ' 6.' | grep -iE 'centos|Red Hat')
    if [ "${centos6_check}" ]; then
        echo "xp面板不支持Centos6，请更换Centos7/8或更高版本的系统"
        exit 1
    fi
fi

if grep -qi 'ubuntu' /etc/os-release; then
    # ubuntu16以下不支持安装
    ubuntu_check=$(cat /etc/issue | grep Ubuntu | awk '{print $2}' | cut -f 1 -d '.')
    if [ "${ubuntu_check}" ] && [ "${ubuntu_check}" -lt "16" ]; then
        echo "xp面板不支持Ubuntu ${ubuntu_check}，请更换Ubuntu18/20或更高版本的系统"
        exit 1
    fi
fi

# 如果不存在/etc/hostname文件，则判断${hostname}变量是否为空，把${hostname}写入/etc/hostname
if [ ! -f "/etc/hostname" ]; then
    if [ -n "${hostname}" ]; then
        echo "${hostname}" > /etc/hostname
    else
        echo "无法安装xp面板，获取主机名失败，请设置hostname后重新安装"
        exit 1
    fi
fi
hostname_check=$(cat /etc/hostname)
if [ -z "${hostname_check}" ]; then
    echo "无法安装xp面板，因为当前主机名hostname为空，请设置hostname后重新安装"
    exit 1
fi

if grep -qi 'centos' /etc/os-release; then
    echo "正在初始化环境，请耐心等待..."
    sudo yum makecache fast &>/dev/null
    sudo yum reinstall -y ca-certificates openssl-devel &>/dev/null
    sudo update-ca-trust force-enable &>/dev/null
    sudo update-ca-trust extract &>/dev/null
elif grep -qi 'ubuntu' /etc/os-release; then
    echo "正在初始化环境，请耐心等待..."
    ub22=$(cat /etc/issue | grep "Ubuntu 22")
    ub24=$(cat /etc/issue | grep "Ubuntu 24")
    if [ "${ub22}" ] || [ "${ub24}" ]; then
        apt-get remove -y needrestart &>/dev/null
    fi
    sudo DEBIAN_FRONTEND=noninteractive apt-get update -y &>/dev/null
    sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --reinstall --force-yes ca-certificates libssl-dev &>/dev/null
    sudo update-ca-certificates &>/dev/null
fi

inst_url="https://dl.xp.cn/dl/xp/xp-installer"

if command -v curl &>/dev/null; then
    curl -O ${inst_url}
elif command -v wget &>/dev/null; then
    wget -O ./xp-installer ${inst_url}
else
    if grep -qi 'centos' /etc/os-release; then
        sudo yum install -y curl &>/dev/null
    elif grep -qi 'ubuntu' /etc/os-release; then
        sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --force-yes curl &>/dev/null
    fi
    echo "系统缺少必要组件curl，已自动安装，正在继续..."
    curl -O ${inst_url}
fi

chmod +x xp-installer
sudo ./xp-installer $@
