#!/bin/bash
## Usage
# 如果虚机上的shell里面不能执行sudu,这个脚本就能派上用场,在root用户下执行此脚本,也就绕过sudo限制了
## ./checkService.sh ztsjxxxt.jar "/usr/local/jar" ztsjxxxt "/home/ubuntu" "production/investigate/backEnd"


fileName=$1
projectPath=$2
serviceName=$3
workPath=$4
ossLogPath=$5
preName="${fileName%.*}"

protal=obs

PATH=PATH:/usr/bin:/usr/sbin:/usr/local/bin

if [ ! -d $workPath ]; then
  echo workPath $workPath not exist!
  exit 1
fi


function uploadLog()
{
  ctype=$1
  identify=$2
  count=$3
  echo "current user is ${USER}"
  echo "current log is " ${workPath}/${identify}.log
  journalctl -n $count -xe -${ctype} $identify | grep -wv " at " > ${workPath}/${identify}.log
  ossutil cp -f ${workPath}/${identify}.log  ${protol}://${ossLogPath}/logs/${identify}.log
  if [ $? -eq 0 ]; then
    echo "ok: log ${identify} uploaded to oss!"
    return 0
  else
    echo "error: upload log ${identify} to oss failed!"
    return 1
  fi
}

function compare(){
  cd $workPath
  echo "current path: $(pwd)"
  if [ ! -f "$fileName" ];then
    echo "checkService 文件 $fileName 不存在1!"
    return 1
  fi

  oriSum=$(md5sum $fileName)
  oriSum="${oriSum%  *}"
  echo "origin local temp file $fileName md5sum: |${oriSum}|"

  if [ ! -d "$projectPath" ]; then
    echo "文件夹 $projectPath 不存在!"
    return -1
  fi

  cd $projectPath
  desSum=""
  if [ ! -f "$fileName" ];then
    cp $workPath/$fileName .
    return 0
  else
    desSum=$(md5sum $fileName)
    desSum="${desSum%  *}"
    echo "current path: $(pwd)"
    echo "locfile in $projectPath ${fileName} md5sum: |${desSum}|"
  fi

  if [ ${oriSum} = ${desSum} ];then
    #journalctl -n 1000 -xe -t autoDeploy > ${workPath}/autoDeploy.log
   return 0
  else 
   echo $oriSum > ${workPath}/${fileName}_md5.txt
   return 1
  fi
}

function restart(){
  systemctl restart $serviceName
  if [ $? -ne 0 ]; then
    echo "error: systemctl restart ${serviceName} failed!"
    sleep 3
    uploadLog t "autoDeploy" 100
    exit 0
  fi
  echo "ok: systemctl restart ${serviceName} success!"
  ossInfoTempPath=${workPath}/${fileName}_oss.info
  ossInfoProjectPath=${projectPath}/${fileName}_oss.info
  echo ossInfoTempPath: $ossInfoTempPath
  echo ossInfoProjectPath: $ossInfoProjectPath
  rm -f ${ossInfoProjectPath}
  cp ${ossInfoTempPath} ${projectPath} 
  cp ${workPath}/${fileName}_md5.txt ${projectPath}

}

function main(){
  echo " "
  echo "start checkService service"
  compare
  result=$?
  echo "result $result"
  if [ $result = 0 ];then 
      # uploadLog
      echo "local temp file ${fileName} is same with file in ${projectPath} ,no need to replace"
      echo "ok: checkService done"
      echo " "
      exit 0
    elif [ $result = 1 ]; then
      echo "local temp file $fileName is different from ${projectPath}, will replace..."
    else 
      exit 0
  fi
  restart
  sleep 45
  uploadLog u $serviceName 500
  echo "ok: checkService done"
  echo " "
  exit 0
}

main