#!/usr/bin/env bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

_info(){
    printf '\033[1;31;36m%b\033[0m' "$1"
    printf "\n"
}

_error(){
    rm -f envs
    rm -f $0
    printf '\033[1;31;31m%b\033[0m' "$1"
    printf "\n"
    exit 1
}

IsRoot(){
    if [[ ${EUID} -ne 0 ]]; then
        _error "This script must be run as root"
    fi
}

_Get_PM(){
    yum >/dev/null 2>&1
    if [ "$?" -ne 127 ]; then
        PM="yum"
    else
    apt-get >/dev/null 2>&1
    if [ "$?" -ne 127 ]; then
        PM="apt-get"
    else
        _error "Get Package Manager Failed!"
    fi
    fi
}

Is64bit(){
    if [ $(getconf WORD_BIT) = '32' ] && [ $(getconf LONG_BIT) = '64' ]; then
        return 0
    else
        return 1
    fi
}

_check_command_exist(){
    local cmd="$1"
    if eval type type > /dev/null 2>&1; then
        eval type "$cmd" > /dev/null 2>&1
    elif command > /dev/null 2>&1; then
        command -v "$cmd" > /dev/null 2>&1
    else
        which "$cmd" > /dev/null 2>&1
    fi
    rt=$?
    if [ ${rt} -ne 0 ]; then
        _error "$cmd is not installed, please install it and try again."
    fi
}

_install_tools(){
    if [ "${PM}" = "yum" ];then
        yum_depends="epel-release gcc gcc-c++ make perl wget net-tools openssl \
openssl-devel automake psmisc procps zip unzip bzip2 xz tar e2fsprogs"
        yum -y install ${yum_depends}
        yum -y install zlib
        yum -y install zlib-devel
        # Centos8, 开启PowerTools仓库
        dnf -y install dnf-plugins-core >/dev/null 2>&1
        dnf config-manager --enable powertools >/dev/null 2>&1
        dnf config-manager --enable PowerTools >/dev/null 2>&1
        # 安装时间同步工具
        yum -y install ntpdate >/dev/null 2>&1
        dnf -y install chrony >/dev/null 2>&1
    elif [ "${PM}" = "apt-get" ];then
        apt_depends="gcc g++ make perl wget net-tools openssl libssl-dev zlib1g \
zlib1g-dev automake psmisc procps zip unzip bzip2 xz-utils tar e2fsprogs"
        apt-get update -y
        apt-get -y install ${apt_depends}
        apt-get -y install ntpdate >/dev/null 2>&1
    fi
    if ! grep -qE "^/usr/local/lib" /etc/ld.so.conf.d/*.conf; then
        echo "/usr/local/lib" > /etc/ld.so.conf.d/locallib.conf
    fi
    if Is64bit; then
        if ! grep -qE "^/usr/lib/x86_64-linux-gnu" /etc/ld.so.conf.d/*.conf; then
            echo "/lib/x86_64-linux-gnu" > /etc/ld.so.conf.d/x86_64-linux-gnu.conf
            echo "/usr/lib/x86_64-linux-gnu" >> /etc/ld.so.conf.d/x86_64-linux-gnu.conf
            echo "/usr/local/lib/x86_64-linux-gnu" >> /etc/ld.so.conf.d/x86_64-linux-gnu.conf
        fi
    else
        if ! grep -qE "^/usr/lib/i386-linux-gnu" /etc/ld.so.conf.d/*.conf; then
            echo "/lib/i386-linux-gnu" > /etc/ld.so.conf.d/i386-linux-gnu.conf
            echo "/usr/lib/i386-linux-gnu" >> /etc/ld.so.conf.d/i386-linux-gnu.conf
            echo "/usr/local/lib/i386-linux-gnu" >> /etc/ld.so.conf.d/i386-linux-gnu.conf
        fi
    fi
    ldconfig

    _check_command_exist "gcc"
    _check_command_exist "g++"
    _check_command_exist "make"
    _check_command_exist "wget"
    _check_command_exist "perl"
    _check_command_exist "netstat"
    _check_command_exist "openssl"
    _check_command_exist "automake"
    _check_command_exist "killall"
    _check_command_exist "pkill"
    _check_command_exist "zip"
    _check_command_exist "unzip"
    _check_command_exist "xz"
    _check_command_exist "tar"
    _check_command_exist "chattr"
    _check_command_exist "lsattr"
    _check_command_exist "free"
}

Set_firewall() {
# firewall rules
firewall-cmd --get-default-zone > /dev/null 2>&1
if [[ $? == 0 ]];then
    firewall-cmd --set-default-zone=public > /dev/null 2>&1
    firewall-cmd --permanent --zone=public --add-port=22/tcp > /dev/null 2>&1
    firewall-cmd --permanent --zone=public --add-port=21/tcp > /dev/null 2>&1
    firewall-cmd --permanent --zone=public --add-port=55000-60000/tcp > /dev/null 2>&1
    firewall-cmd --permanent --zone=public --add-port=80/tcp > /dev/null 2>&1
    firewall-cmd --permanent --zone=public --add-port=443/tcp > /dev/null 2>&1
    firewall-cmd --permanent --zone=public --add-port=3306/tcp > /dev/null 2>&1
    firewall-cmd --permanent --zone=public --add-port=6379/tcp > /dev/null 2>&1
    firewall-cmd --permanent --zone=public --add-port=999/tcp > /dev/null 2>&1
    firewall-cmd --permanent --zone=public --add-port=6588/tcp > /dev/null 2>&1
    firewall-cmd --reload > /dev/null 2>&1
fi
}

Set_iptables() {
# iptables rules
iptables -L -n >/dev/null 2>&1
if [[ $? == 0 ]];then
    iptables -A INPUT -p icmp --icmp-type 8 -j ACCEPT >/dev/null 2>&1
    iptables -A INPUT -p tcp -m state --state RELATED,ESTABLISHED -j ACCEPT >/dev/null 2>&1
    iptables -A INPUT -p tcp --dport 21 -m state --state NEW,ESTABLISHED -j ACCEPT >/dev/null 2>&1
    iptables -A INPUT -p tcp -m multiport --dports 22,80,443,999,3306,6379,6588,55000:60000 -j ACCEPT >/dev/null 2>&1
    iptables -A INPUT -p udp -m udp --sport 53 -j ACCEPT >/dev/null 2>&1
    if [ -d /etc/sysconfig ]; then
        iptables-save > /etc/sysconfig/iptables
    fi
    if [ -d /etc/network/if-pre-up.d ]; then
        iptables-save > /etc/iptables.rules
        cat > /etc/network/if-pre-up.d/iptables <<EOF
#!/bin/bash
iptables-restore < /etc/iptables.rules
EOF
        chmod +x /etc/network/if-pre-up.d/iptables
    fi
fi
}

GetIp(){
    #[ -z "${ipv4}" ] && ipv4=$( wget -qO- -t1 -T2 ip.hws.com/getip.asp )
    [ -z "${ipv4}" ] && ipv4=$( wget -qO- -t1 -T2 apilm.hws.com/lm/getip.asp )
    [ -z "${ipv4}" ] && ipv4=$( wget -qO- -t1 -T2 ipv4.icanhazip.com )
    [ -z "${ipv4}" ] && ipv4=$( wget -qO- -t1 -T2 ipinfo.io/ip )
    if [ "${ipv4}" == "" ]; then
        ipv4='127.0.0.1'
    fi
    printf -- "%s" "${ipv4}"
}

RandomInt6() {
    tr -dc "0-9" < /dev/urandom | head -c 6
}

RandomInt() {
    tr -dc "0-9" < /dev/urandom | head -c 3
}

RandomString(){
    tr -dc "0-9A-Za-z" < /dev/urandom | head -c 35
}

RandomString4() {
    tr -dc "a-z" < /dev/urandom | head -c 4
}

Set_envs() {
    cat >envs<<EOF
#!/bin/bash
umask 022
EOF
    source envs
}

VERSION="V3.0.0"
DOWNLOAD_URL="http://d.hws.com/linux/master/release/3.0.0.bin"

Set_envs
IsRoot
Username="admin"$(RandomInt)
Password=$(RandomString)
Point=$(RandomString4)
InternetIp=$(GetIp)
IntranetIp=$(ip addr | grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -E -v "^127\.|^255\.|^0\." | head -n 1)

while :
do
    clear
    echo
    echo "+----------------------------------------------------------------------"
    echo "| 护卫神·主机大师/HwsMaster ${VERSION} For CentOS/Ubuntu/Debian"
    echo "+----------------------------------------------------------------------"
    echo "| Copyright © 2004-3999 Hws (https://www.hws.com) All rights reserved."
    echo "+----------------------------------------------------------------------"
    echo
    echo "+----------------------------------------------------------------------"
    echo -n "您想要将面板安装在默认路径 /hws.com/hwsmaster 吗?
Do you want to install HwsMaster to the /hws.com/hwsmaster directory now? (y/n): "
    read user_select
    if [[ "${user_select}" == "y" || "${user_select}" == "Y" ]]; then
        InstallPrefix=/hws.com/hwsmaster
        break
    elif [[ "${user_select}" == "n" || "${user_select}" == "N" ]]; then
        while :
        do
            echo -n "请输入绝对路径
Input your absolute path(eg: /hws.com/hwsmaster): "
            read user_input
            mkdir -p ${user_input}
            if [ "$?" -ne 0 ]; then
                echo "创建目录失败,请更换一个目录名重试
The directory name you entered is invalid,Please try again."
                continue
            fi
            InstallPrefix=${user_input}
            break
        done
        break
    else
        continue
    fi
done

_Get_PM
_install_tools

mkdir -p $InstallPrefix
if [ "$?" -ne 0 ]; then
    _error "[ERROR]: Mkdir $InstallPrefix failed."
fi

# 重新下载
if [ -e "/etc/init.d/hws" ]; then
    /etc/init.d/hws stop > /dev/null 2>&1
fi
rm -f $InstallPrefix/hwspanel
wget --no-check-certificate -cv -t3 -T60 -O "$InstallPrefix/hwspanel" ${DOWNLOAD_URL}
if [ "$?" -ne 0 ]; then
    _error "[ERROR]: Downloading falied."
fi
chmod +x $InstallPrefix/hwspanel
if [ "$?" -ne 0 ]; then
    _error "[ERROR]: chmod +x failed."
fi

if [ -e "$InstallPrefix/hws.db" ]; then
    $InstallPrefix/hwspanel install
    if [ "$?" -ne 0 ]; then
        _error "[ERROR]: Install sysv script failed."
    fi

    /etc/init.d/hws start
    if [ "$?" -ne 0 ]; then
        _error "[ERROR]: Start failed."
    fi

    echo "
==================================================================
护卫神·主机大师 覆盖安装成功！
==================================================================
当前版本： ${VERSION}
覆盖安装不会重新设置入口和创建登录帐号
请使用原来的信息登录面板

常用命令：
 （1）启动软件： /etc/init.d/hws start
 （2）停止软件： /etc/init.d/hws stop
==================================================================
HwsMaster Installation successfully!
==================================================================
Version: ${VERSION}
Overwriting installation will not reset the entrance and create a login account
Please use the original information to log in to the panel

Common commands:
 (1)Start the soft: /etc/init.d/hws start
 (2)Stop the soft:  /etc/init.d/hws stop
=================================================================="
_info "cat $InstallPrefix/readme"
cat $InstallPrefix/readme
else
    # 如果数据库不存在则创建用户并设置入口点
    $InstallPrefix/hwspanel install
    if [ "$?" -ne 0 ]; then
        _error "[ERROR]: Install sysv script failed."
    fi
    $InstallPrefix/hwspanel useradd -username ${Username} -password ${Password}
    if [ "$?" -ne 0 ]; then
        _error "[ERROR]: Add user failed."
    fi
    $InstallPrefix/hwspanel point -set /${Point}
    if [ "$?" -ne 0 ]; then
        _error "[ERROR]: Set security point failed."
    fi

    /etc/init.d/hws start
    if [ "$?" -ne 0 ]; then
        _error "[ERROR]: Start failed."
    fi

    Set_iptables
    Set_firewall

    echo "
==================================================================
护卫神·主机大师 安装成功！（请妥善保管以下信息）
==================================================================
当前版本： ${VERSION}
安装路径： ${InstallPrefix}
外网地址： http://${InternetIp}:6588/${Point}
内网地址： http://${IntranetIp}:6588/${Point}
管理用户： ${Username}
管理密码： ${Password}
注意事项：
 （1）如果无法访问面板，请在防火墙/安全组开放[6588|999|80|443|21|55000-60000]端口（云主机还需到云厂商“控制台”开放此端口）。
 （2）推荐使用IE11、Chrome、Microsoft Edge等浏览器访问。
常用命令：
 （1）启动软件： /etc/init.d/hws start
 （2）停止软件： /etc/init.d/hws stop
==================================================================
HwsMaster Installation successfully! (Please keep the following information properly)
==================================================================
Version: ${VERSION}
InstallPrefix: ${InstallPrefix}
Internet URL: http://${InternetIp}:6588/${Point}
Intranet URL: http://${IntranetIp}:6588/${Point}
Username: ${Username}
Password: ${Password}
Notice:
 (1)If you cannot access the panel, please open the port [6588|999|80|443|21|55000-60000] in the firewall / security group (the virtual machine needs to open the ports to the cloud manufacturer's "console").
 (2)It is recommended to use ie11, chrome, Microsoft edge and other browsers.
Common commands:
 (1)Start the soft: /etc/init.d/hws start
 (2)Stop the soft:  /etc/init.d/hws stop
==================================================================" | tee $InstallPrefix/readme
fi

rm -f envs
rm -f $0
