#!/bin/bash
tbasepath=$(cd `dirname $0`; pwd)
basepath=$tbasepath/..
spid=$tbasepath/command.pid
versionPath=$1

updateBin(){
 version=$(cat $tbasepath/version)
 len=${#basepath}
 if [ $len -gt 1 ] ; then
      mkdir -p  $basepath/$version/bin
      mv -f $basepath/bin/* $basepath/$version/bin
 fi
 cp -rf $basepath/$versionPath/bin/* $tbasepath
 chmod +x $tbasepath/*.sh
}

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