#!/bin/bash
#当前脚本执行文件夹，即rootPath/upgradeBin
ubasepath=$(cd `dirname $0`; pwd -P)
#rootPath/bin
tbasepath=${ubasepath%/*}/bin
#当前版本号，rootPath/bin/version
version=$(cat $tbasepath/version)
cd $tbasepath/..
#根目录
basepath=$tbasepath/..
#升级目标版本
versionPath=$1
#当前版本目录下的bin目录，rootPath/version/bin
currentVersionBinPath=$basepath/$version/bin
spid=$tbasepath/command.pid

updateBin(){
 version=$(cat $tbasepath/version)
 len=${#basepath}
 if [ $len -gt 1 ] ; then
     #检测当前版本目录下的bin目录是否存在
     if [ ! -d $currentVersionBinPath ];then
       #不存在则创建
       mkdir -p $currentVersionBinPath
       #将当前根目录下的bin目录拷贝到版本目录下(解决无法切换回原始版本的问题)
       cp -rf $tbasepath/* $currentVersionBinPath/
     fi
     cp -rf $basepath/$versionPath/bin/* $tbasepath/
     chmod +x $tbasepath/*.sh
 fi
}

currentPId(){
    if [ -e $spid ];then
        pid=`cat $spid`
        tpid=`ps --no-headers -fp $pid|grep java|wc -l`
        if [ $tpid -ne 1 ];then
           pid=""
        fi
    else
        pid=""
    fi
    echo $pid
}

pid=$(currentPId)
echo "pid is $pid"
if [ "$pid" = "" ]; then
	sh $tbasepath/start.sh stop
	updateBin
	sh $tbasepath/start.sh start
else
      mddName=$(systemctl status $pid|grep -Eo "\w+.service"|head -1)
	    echo "mddName is $mddName"
      if [ "$mddName" = "mdd.service" ]; then
		    (timeout 3 sudo -v ) && (updateBin && sudo systemctl restart $mddName) || (updateBin && sh $tbasepath/start.sh stop)
      else
        sh $tbasepath/start.sh stop > /dev/null
        updateBin
        sh $tbasepath/start.sh start > /dev/null
      fi
fi
rm -rf $basepath/upgradeBin