#!/bin/bash
ubasepath=$(cd `dirname $0`; pwd -P)
tbasepath=${ubasepath%/*}/bin
version=$(cat $tbasepath/version)
cd $tbasepath/..
basepath=$tbasepath/..
versionPath=$1
spid=$tbasepath/command.pid

updateBin(){
 version=$(cat $tbasepath/version)
 len=${#basepath}
 if [ $len -gt 1 ] ; then
     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
        updateBin
        sh $tbasepath/start.sh start
      fi
fi
rm -rf $basepath/upgradeBin