#!/bin/bash

#版本
verson=7.2.2

#要部署的分支
branch=master

#源文件存储目录
source_dir=/opt/erp/source/api

#程序运行时目录
server_dir=/opt/erp/server
mkdir -p $server_dir"/logs/"
#要运行的api
apis=("server")
# 杀死进程
killone(){
ps -ef |grep java |grep $1  |grep -v 'grep'|awk '{print $2}'  | xargs kill -9
echo '停止'$1
}
# 启动程序
startone(){
nohup java -Xmx512m -Xms256m -Xss1024k  -jar $1"-"$verson.jar > $server_dir"/logs/"$1".out"  2>&1 &
echo '启动'$1
}
# 默认全部启动
startall="yes"
for api_name in  ${apis[@]}
do
if [[ "$1" != "" && "$1" = $api_name  && "$1" != "dontbuild" ]]
then
startall="no"
break
fi
done

echo "startall is "$startall

if [[ "$startall" = "yes" ]]; then
#杀死进程
for api_name in  ${apis[@]}
do
killone "$api_name"
echo "$api_name stop success"

    done
else
killone "$1"
fi

#检测端口状态
checkPort(){
r=`netstat -ntlp | awk '{print $4}' | grep :$1`
if [ "$r" == "" ]
then
return 0
else
return 1
fi

}

if [ "$1" != "dontbuild" ]
then
#更新源码
cd  $source_dir
git reset --hard $branch
git pull

rm -rf /opt/erp/source/api/module-erp/target
mvn -T 1C clean install -DskipTests -f pom.xml
rm -rf $server_dir"/*.jar"

    for api_name in  ${apis[@]}
    do
        mv $source_dir"/"$api_name"/target/"$api_name"-"$verson.jar $server_dir
    done
else
echo "不构建，直接重启"    
fi

cd $server_dir

if [[ "$startall" == "yes" ]]; then
for api_name in  ${apis[@]}
do
startone "$api_name"
done
else
startone "$1"
fi

#进度条
progressBar(){

label=('|' '/' '-' '\')

per=$1
ii=0
str=''
myTimes=$2
text=$3
let index=myTimes%4
#拼接#字
while [ $ii -le  $per ]
do
str=#$str
let ii++
done

printf "[%-100s]%d%%  %s %s\r" $str $per ${label[$index]} $text


if [[ $per == 100 ]]; then
echo
fi

}

#声明所有的服务和端口号，以便检测
serviceMap["9999"]="server"


totalPer=0

#是否全部启动成功的标识
all_is_ok=""
last_text=''
times=0
processNum=0
processItem=100/1 #七个任务中每个任务所占进度
while :
do
all_is_ok="yes"
progressBar $totalPer $times $last_text

    #100次检查一下
    checked=$(($times%100))

    if [[ $checked == 0 ]]; then
        for key in ${!serviceMap[*]};do
           checkPort "$key"
           started_result=`echo $?`
           if [ "$started_result" == "1" ]
           then
             processNum=$(($processNum+1))
             #每启动一个服务进度
             totalPer=$(($processNum*$processItem))
             #显示启动成功的程序
             printf "%-57s%57s\n" ${serviceMap[$key]} '已启动' | sed 's/[ ]/-/g'
             #将启动成功的服务移除掉
             unset serviceMap["$key"]
           fi
        done
    fi


    sleep 0.1
    let times++
    if [[ ${#serviceMap[*]} == 0 ]]; then
        progressBar 100 1 "全部启动完成"
        break
    fi
done