#/bin/bash

# 初始化Ubuntu 22系统

if [ "$(id -u)" -ne 0 ] ; then
    echo "You must run this script as root. Sorry!"
    exit 1
fi

echo -e "Init Server And Install System Pkg ...... \n"

sleep 1

echo "\$nrconf{restart} = 'a';" >> /etc/needrestart/needrestart.conf
flag_log_path=/tmp/install_flag.log

if [ ! -f ${flag_log_path} ];then
    touch ${flag_log_path}
fi

if [ -z `grep -w 'aptGet' ${flag_log_path}` ];then
    apt-get update -y 
    apt-get upgrade -y  

    apt-get install -y  iputils-ping vim wget zip unzip cronolog bison libpcre3-dev libssl-dev libjemalloc2 \
    libjemalloc-dev lrzsz autoconf pkg-config bzip2 libncurses-dev tmpreaper libtool  libxml2 gdb  subversion cmake  \
    ntp make build-essential  tree pigz pbzip2  python3-pip unixodbc unixodbc-dev libwxgtk3.0-gtk3-dev libwxgtk-webview3.0-gtk3-dev \
    xsltproc fop ament-cmake-xmllint libncurses5-dev libprotobuf-dev libmysqlclient-dev

    pip3 install beautifulsoup4 tqdm python-magic requests

    echo 'aptGet' >> ${flag_log_path}
fi

_REPO_LST_=180.184.179.168
_INIT_URL_=http://${_REPO_LST_}/initUbuntu/
wget -c -r -np -nH -x -k -L -p -q ${_INIT_URL_}

echo -e "\n\n"

function ChangeConf()
{
    echo "有配置需要变更,确定变更好了吗?(Y/n):"
    echo ""

    read isconf_
    echo

    if [ -z ${isconf_} ] || [ ${isconf_//[Yy]/y} != "y" ]; then
        echo "配置文件: [ ./initUbuntu/config/init.yaml ]"
        exit
    fi

}

ChangeConf

function CheckInstall()
{
    echo "确定要安装服务器吗?(Y/n):"

    read isinstall_
    echo

    if [ -z ${isinstall_} ] || [ ${isinstall_//[Yy]/y} != "y" ]; then
        echo "已退出安装, BYE~"
        exit
    fi

    echo "开始安装服务器 ... ..."

    python3 ./initUbuntu/install_server.py
}

CheckInstall

CheckInstallCode=`echo $?`

function Reboot()
{
    echo -e "\n确定要重启服务器吗?(Y/n):"

    read isinstall_
    echo

    if [ -z ${isinstall_} ] || [ ${isinstall_//[Yy]/y} != "y" ]; then
        echo "暂不重启, BYE~"
        exit
    fi

    echo "开始重启服务器 ... ..."

    reboot
}

function configEtcHost()
{
    echo "配置/etc/hosts......"

    cat << EOF >> /etc/hosts
127.0.0.1 BACKSTAGE
127.0.0.1 API-SERVER
127.0.0.1 REDIS-SERVER
127.0.0.1 DB-DYN-SERVER
127.0.0.1 DB-SYS-SERVER
127.0.0.1 MONGODB-SERVER
127.0.0.1 GATEWAY-SERVER
127.0.0.1 RABBITMQ-SERVER
127.0.0.1 PLATFORM-SERVER
127.0.0.1 nestAnalysis
127.0.0.1 nestMail
127.0.0.1 nestDBLink
127.0.0.1 NACOS-SERVER
EOF
}

if [ ${CheckInstallCode} -eq 0 ];then
    configEtcHost
    Reboot
fi
