#!/bin/bash

if  [ $# -lt 2 ]; then
        echo "please using 'sh script.sh  group  hostname (hw)'"
        exit
fi

group=$1
hostname=$2
region=$3

if [  ! -f "/etc/redhat-release" ]; then
        os="ubuntu"
        os_ver=`cat /etc/lsb-release |grep -w 'DISTRIB_RELEASE' |awk -F '=' '{print $2}'`
else
        os="centos"
fi

if [ $os == 'centos' ];then
    yum  install  git -y
elif [ $os == 'ubuntu' ];then
    apt install git -y
fi
if [ ! $region ];then
        cd /usr/local &&  git clone https://sa-public:goodluck1234@sa-newgit.gyyx.cn/sa-private/os_unify_script.git
else
        cd /usr/local && wget http://119.28.82.130/test/os_unify_script.zip && unzip os_unify_script.zip
fi
if [ $? != 0 ];then
        echo "项目代码下载失败，请检查！！"
        exit 1
fi

echo $os
chmod +x /usr/local/os_unify_script/*
if [ $os == 'centos' ];then
    #/bin/sh /usr/local/os_unify_script/osinit_centos.sh
    /bin/sh /usr/local/os_unify_script/os_new_v2.sh $group  $hostname >>/tmp/osinstall.log
elif [ $os == 'ubuntu' ];then
    if [ $os_ver == '20.04' ];then
    	sed -i  '/needrestart.conf/d' /usr/local/os_unify_script/osinit_ubuntu.sh
	sed -i  '/python2.7.18.zip/d' /usr/local/os_unify_script/config.ini
    fi
    bash /usr/local/os_unify_script/osinit_ubuntu.sh $group $hostname >>/tmp/osinstall.log
fi

if [ $? != 0 ];then
        echo "基础环境脚本运行异常，请检查！"
        exit 1
else
        echo "基础环境脚本运行完成，日志文件：/tmp/osinstall.log"
fi

if [ $os == 'centos' ];then
    cd /usr/local/os_unify_script  && python   maininit.py all  $group  $hostname >>/tmp/osinstallpackage.log
elif [ $os == 'ubuntu' ];then
    cd /usr/local/os_unify_script  && python3   maininit.py all  $group  $hostname >>/tmp/osinstallpackage.log
fi

if [ $? != 0 ];then
        echo "基础服务安装脚本运行异常，请检查！"
        exit 1
else
        echo "软件环境脚本运行完成，日志文件：/tmp/osinstallpackage.log"
fi

# 如果有region参数，则代表为其他地域机器，需要通过公网连接各个服务端
if [ $region ];then
	# 将第四版监控中心端解析为公网lb
	echo "119.28.82.130 server.pigeon.gyyx.cn" >>/etc/hosts

	# 将elves配置文件中本机的ip替换为公网ip
	ip=`curl ip.sb`
	sed -i  's/\("asset": "\).*/\1'"$ip"'",/g'   /usr/local/elves-agent/conf/cfg.json
	sed -i  's/\("ip": "\).*/\1'"$ip"'",/g'   /usr/local/elves-agent/conf/cfg.json

	# 将elves中心端内网ip替换为公网ip
        	sed -i  's/\("addr": "\).*/\1'"154.8.227.208"'",/g'   /usr/local/elves-agent/conf/cfg.json
        	sed -i  's#\("appsdownloadaddr": "\).*#\1'"http://154.8.227.208/"'",#g'   /usr/local/elves-agent/conf/cfg.json
        	/usr/local/elves-agent/control restart

	# 将sa的git仓库解析为公网
	echo "120.53.244.213 git-sa.ops.gyyx.cn" >>/etc/hosts
fi
