#!/bin/bash
base_dir=/home/taxsys/
src_dir=${base_dir}"git_src/"
deploy_dir=${base_dir}
deploy_log_dir=/data/117_logs/cloudlogs/
bak_dir=${base_dir}"bak_jar/"
project=tax-sys
branch=master
ver_file=${base_dir}"gitVer.info"
user=taxsys
#e_server=172.16.50.94
e_server=127.0.0.1
# start java -jar  parameter
start_para="--spring.cloud.config.profile=prd"
#start_para=""
clientList=(sign-startup token-startup user-startup scan-startup taxfile-startup zone-startup tax-service-center-gateway tax-websocket-startup)


# check bakdir ,if not exists,make it
if [ ! -d ${ver_dir} ]; then
  mkdir -p ${ver_dir}
fi

if [ ! -d ${bak_dir} ]; then
  mkdir -p ${bak_dir}
fi
# check src dir,if not exists,exit
if [ -d ${src_dir}${project} ]; then
  cd ${src_dir}${project}
else
  echo "project ${src_dir}${project} is not exist!"
  exit 32
fi

# update src code to latest
update_src()
{
  # get head version
  git checkout ${branch}
  git reset --hard HEAD
  git_info=`git pull`
  echo $git_info >git_info
  git_stat=`git pull`
  echo $git_stat >git_stat
  # check whether last version,if not,exit
  if [[ "${git_stat}" =~ 'Already up to date' ]] || [[ "${git_stat}" =~ 'Already up-to-date' ]]; then
    echo "git update successfull!"
  else
    echo "git update failed,please check it!"
    echo ${git_stat}
    exit 51
  fi
  src_ver=`git rev-list HEAD --abbrev-commit --max-count=1`
}
# mvn bulid the project
build_src()
{
  update_src
  if [ -f $ver_file ]; then
    gv=`cat $ver_file`
  else
    gv=no
  fi
  if [[ ${gv} =~ "$src_ver" ]]; then
    echo "build is already the newest!"
  else
    echo "begin to build src..."
    mvn_info=`mvn clean install`
    if [[ "${mvn_info}" =~ 'BUILD SUCCESS' ]]; then
       echo "mvn build successfull!"
     else
       echo "mvn build failed,please check it!"
       echo ${mvn_info}
       exit 74
    fi
    echo ${src_ver} > ${ver_file}
  fi
 }

make_deploy_jar()
{
  for aj in `find ${src_dir}${project} -name "*.jar" | grep -v "source" | grep SNAPSHOT | egrep -e "tax-service-center" -e "startup"`
    do
      aj_name=${aj##*/}
      check_aj=`find ${deploy_dir} -maxdepth 1 -name "*${aj_name}" | wc -l | sed s/[[:space:]]//g`
      if [ "${check_aj}" -eq 0 ]; then
        echo "lack ${aj_name},copy it ..."
        cp ${aj} ${deploy_dir}${src_ver}"_"${aj_name}
      fi
    done
}

is_registry_ok()
{
  r_code=0
  for i in `seq 30`
  do
    r_code=`curl -s -I --connect-timeout 1 -m 3 http://${e_server}:8761/ | grep HTTP | awk '{print $2}'`
    if [[ ${r_code} == 200 ]]; then
      echo "connect to regitstry server ok!"
      break
    else
      echo "wait registry starting,sleep 2s..."
      sleep 2
    fi
  done
  if [[ ${r_code} != 200 ]]; then
    echo "regtistry server is not availabe,please check it,exit!"
    exit 109
  fi
}

is_config_ok()
{
  is_registry_ok
  c_code=0
  for i in `seq 30`
    do
      c_code=`curl -s -I --connect-timeout 1 -m 3 http://${e_server}:10200/info/ | grep HTTP | awk '{print $2}'`
      if [[ ${c_code} == 200 ]]; then
        echo "connect to config server ok!"
        break
      else
        echo "wait config starting,sleep 2s..."
        sleep 2
      fi
    done
  if [[ ${c_code} != 200 ]]; then
    echo "config server is not availabe,please check it,exit!"
    exit 130
  fi
}

stop_server()
{
  echo "stop server..."
  for i in `ps -ef | grep ${user} | grep jar | egrep -e tax-service-center-registry -e tax-service-center-config | awk '{print $2}'`
  do
    kill -9 $i
  done
}

stop_client()
{
  if [ $1 = "all" ]; then
    echo "stop all client..."
    for cli in ${clientList[*]}
    do
      for i in `ps -ef | grep ${user} | grep jar | egrep -e ${cli} | awk '{print $2}'`
      do
        kill -9 $i
      done
    done
    #for i in `ps -ef | grep ${user} | grep jar | egrep -e token-startup -e sign-startup -e user-startup -e zone-startup -e scan-startup -e taxfile-startup -e tax-service-center-gateway | awk '{print $2}'`
    #do
    #  kill -9 $i
    #done
  else
    echo "stop client $1"
    for i in `ps -ef | grep ${user} | grep jar | grep "$1" | awk '{print $2}'`
    do
      kill -9 $i
    done
  fi
}

start_server()
{
  echo "start server..."
  reg_jar_wc=`find ${deploy_dir} -maxdepth 1 -name *tax-service-center-registry*.jar | wc -l | sed s/[[:space:]]//g`
  cfg_jar_wc=`find ${deploy_dir} -maxdepth 1 -name *tax-service-center-config*.jar | wc -l | sed s/[[:space:]]//g`
  pid_reg=`ps -ef | grep tax-service-center-registry | grep java | grep -v grep |  wc -l | sed s/[[:space:]]//g`
  pid_cfg=`ps -ef | grep tax-service-center-config | grep java | grep -v grep |  wc -l | sed s/[[:space:]]//g`
  if [ "${reg_jar_wc}" -eq 0 ]; then
    echo "cannot find tax-service-center-registry! exit..."
    exit 176
  else
    if [ ${pid_reg} -eq 0 ];then
      reg_jar=`ls -lt ${deploy_dir} | grep "tax-service-center-registry.*\.jar" | head -1 | awk '{print $NF}'`
      nohup java -Xmx512M -Xms512M -jar ${deploy_dir}${reg_jar} ${start_para}>${deploy_log_dir}"registry.log" 2>&1 &
    else
      echo "center registry is running,please check it!"
    fi
  fi

  if [ "${cfg_jar_wc}" -eq 0 ]; then
    echo "cannot find tax-service-center-config! exit..."
    exit 188
  else
    if [ ${pid_cfg} -eq 0 ];then
      is_registry_ok
      cfg_jar=`ls -lt ${deploy_dir} | grep "tax-service-center-config.*\.jar" | head -1 | awk '{print $NF}'`
      nohup java -Xmx256M -Xms256M -jar ${deploy_dir}${cfg_jar} ${start_para}>${deploy_log_dir}"/config.log" 2>&1 &
    else
      echo "center config is running,please check it!"
    fi
  fi
}

start_client()
{
  if [ ${1}x = "allx" ]; then
    echo "start client..."
    #for sc in sign-startup token-startup user-startup scan-startup taxfile-startup zone-startup tax-service-center-gateway;
    for sc in ${clientList[*]}
    do
      is_here=`find ${deploy_dir} -maxdepth 1 -name *${sc}*.jar | wc -l | sed s/[[:space:]]//g`
      pid_cl=`ps -ef | grep ${sc} | grep java | grep -v grep |  wc -l | sed s/[[:space:]]//g`
      if [ ${is_here} -ne 0 ]; then
        cl_jar=`ls  -lt ${deploy_dir} | grep "${sc}.*\.jar" | head -1 | awk '{print $NF}'`
        if [ ${pid_cl} -eq 0 ]; then
           is_config_ok
           echo "start client ${sc} ..."
           if [ "${sc}" = "sign-startup" -o "${sc}"="token-startup" -o "${sc}"="taxfile-startup" ]; then
             jvm_arg="-Xmx768M -Xms768M"
           else
             jvm_arg="-Xmx384M -Xms384M"
           fi
           nohup java ${jvm_arg} -jar ${deploy_dir}${cl_jar} ${start_para}>"${deploy_log_dir}${sc}.log" 2>&1 &
        else
           echo "${sc} is running,please check it"
        fi
      fi
    done
  else
      is_here=`find ${deploy_dir} -maxdepth 1 -name *${1}*.jar | wc -l | sed s/[[:space:]]//g`
      pid_cl=`ps -ef | grep ${1} | grep java | grep -v grep |  wc -l | sed s/[[:space:]]//g`
      if [ ${is_here} -ne 0 ]; then
        cl_jar=`ls  -lt ${deploy_dir} | grep "${1}.*\.jar" | head -1 | awk '{print $NF}'`
        if [ ${pid_cl} -eq 0 ]; then
           is_config_ok
           echo "start client ${1} ..."
           if [ "${1}" = "sign" -o "${1}" = "token" ]; then
             jvm_arg="-Xmx768M -Xms768M"
           else
             jvm_arg="-Xmx384M -Xms384M"
           fi
           nohup java ${jvm_arg} -jar ${deploy_dir}${cl_jar} ${start_para}>"${deploy_log_dir}${1}.log" 2>&1 &
        else
           echo "${1} is running,please check it"
        fi
      fi
  fi
}


update_server()
{
  build_src
  echo "deploy server to the lastest version!"
  bak_da=`date +%Y%m%d_%H%M%S`
  if [ ! -d ${bak_dir}${bak_da} ]; then
    mkdir -p ${bak_dir}${bak_da}
  fi
  if [ "$1"x = "serverallx" ]; then
    stop_client all
    stop_server
    for sc in registry config;
    do
      server_jar=`find ${src_dir}${project} -name "*tax-service-center-${sc}*.jar" ! -name "*source*"`
      server_jar_name=${server_jar##*/}
      find ${deploy_dir} -maxdepth 1 -name "*tax-service-center-${sc}*.jar" -exec mv -f {} ${bak_dir}${bak_da} \;
      cp ${server_jar} ${deploy_dir}${src_ver}"_"${server_jar_name}
    done
      make_deploy_jar
      start_server
      start_client all
  elif [ ${1}x = "registryx" -o ${1}x = "configx" ]; then
    server_jar=`find ${src_dir}${project} -name "*tax-service-center-${1}*.jar" ! -name "*source*"`
    server_jar_name=${server_jar##*/}
    stop_client all
    stop_server
    find ${deploy_dir} -maxdepth 1 -name "*tax-service-center-${1}*.jar" -exec mv  -f {} ${bak_dir}${bak_da} \;
    cp ${server_jar} ${deploy_dir}${src_ver}"_"${server_jar_name}
    start_server
    start_client all
  else
    echo "update server para is wrong,must be [all | registry | config]!"
    exit 279
  fi
}



update_client()
{
  build_src
  bak_da=`date +%Y%m%d_%H%M%S`
  if [ ! -d ${bak_dir}${bak_da} ]; then
    mkdir -p ${bak_dir}${bak_da}
  fi
  if [ "$1"x = "clientallx" ]; then
    for sc in ${clientList[*]};
    #for sc in sign-startup token-startup user-startup scan-startup taxfile-startup tax-service-center-gateway zone-startup;
    do
      stop_client ${1}
      find ${deploy_dir} -maxdepth 1 -name "*${sc}*.jar" -exec mv  -f {} ${bak_dir}${bak_da} \;
      myclient=`find ${src_dir}${project} -name "*${sc}*.jar" | grep -v 'archive-tmp' | grep -v "source" | grep SNAPSHOT | egrep -e "startup" -e "gateway"`
      mc=${myclient##*/}
      cp ${myclient} ${deploy_dir}${src_ver}"_"${mc}
      echo "update ${sc} successfully!"
      is_config_ok
      echo "start client ${sc} ..."
      start_client ${1}
    done
    echo ""
  else
    stop_client ${1}
    find  ${deploy_dir} -maxdepth 1 -name "*${1}*.jar" -exec mv -f {} ${bak_dir}${bak_da} \;
    myclient=`find ${src_dir}${project} -name "*${1}*.jar" | grep -v "archive-tmp" | grep -v "source" | grep SNAPSHOT | egrep -e "startup" -e "gateway"`
    echo "path is $myclient"
    mc=${myclient##*/}
    echo "this is $mc"
    cp ${myclient} ${deploy_dir}${src_ver}"_"${mc}
    echo "update ${1} successfully!"
    is_config_ok
    echo "start client ${1} ..."
    start_client ${1}
  fi
}

if [ $# -eq 0 ] || [ $# = 1 -a $1 = "status" ]; then
  echo "jars process status:"
  ps -ef |grep ${user} | grep SNAPSHOT | grep -v grep

elif [ $# = 1 -a $1 = "startserver" ]; then
  echo "Begin to start server(registry first and then config) ..."
  start_server

elif [ $# = 1 -a $1 = "stopserver" ]; then
  echo "Begin to shutdown the server(both stop registry and config) ..."
  stop_server

elif [ $# = 2 ] && [ $1 = "start" -o $1 = "stop" ]; then
  if [[ `echo ${clientList[*]} | tr ' ' '\n' | grep -w "$2" | wc -l` != 0  ]] || [[ $2 == "all" ]]; then
    if [ $1 = "start" ]; then
      echo "Begin to start client $2 ..."
      start_client $2
    elif [  $1 = "stop" ]; then
      echo "Begin to stop client $2 ..."
      stop_client $2
    else
      echo "operation can only be start or stop ..."
    fi
  else
    echo "usage: start/stop $clientList[*]"
    exit 347
  fi
elif [ $# = 1 -a $1 = "startall" ]; then
  echo "Begin to start all jars(server/config/${clientList[*]}) ..."
  start_server
  start_client all

elif [ $# = 1 -a $1 = "stopall" ]; then
  echo "Begin to shutdown all jars(server/config/${clientlist[*]}) ..."
  stop_client all
  stop_server

elif [ $# = 1 -a $1 = "force" ]; then
  echo "Begin to force auto deploy all jars ..."
  rm -rf ${deploy_dir}"*.jar"
  update_src
  build_src
  stop_server
  stop_client all
  make_deploy_jar
  start_server
  start_client all

elif [ $# = 2 -a $1 = "update" ]; then
  echo "Begin to update jar $2 ..."
  if [ $2 = "registry" -o $2 = "config" -o $2 = "serverall" ]; then
    update_server $2
  elif [[ `echo ${clientList[*]} | tr ' ' '\n' | grep -w "$2" | wc -l` != 0  ]] || [[ $2 == "clientall" ]]; then
  #elif [ $2 = "gateway" -o $2 = "token" -o $2 = "user" -o $2 = "sign" -o $2 = "scan" -o $2 = "taxfile" -o $2 = "zone" -o $2 = "clientall" ]; then
    update_client $2
  else
    echo "usage: update [registry | config | ${clientList[*]} serverall | clientall]"
    exit 379
  fi

elif [ $# = 2 -a $1 = "log" ]; then
  echo "begin to watch the log $2 ..."
  thisPara=`echo $2 | sed s/-//g`
  if [ $2 = "registry" -o $2 = "config" ]; then
    tail -200f ${deploy_log_dir}"${2}.log"
  elif [[ `echo ${clientList[*]} | sed s/-//g | tr ' ' '\n' | grep -w "$thisPara" | wc -l` != 0  ]]; then
    tail -200f ${deploy_log_dir}${2}.log
  else
    echo "usage: log [registry | config | ${clientList[*]}]"
    exit 390
  fi

elif [ $# = 1 -a $1 = "status" ]; then
  echo "jars process status:"
  ps -ef |grep ${user} | grep SNAPSHOT | grep -v grep

elif [ $# = 1 -a $1 = "updatesrc" ]; then
  update_src
  build_src
else
  echo "Your param is wrong!"
  echo "usage:"
  echo "$0 [ startserver | stopserver | startall | stopall | force | status ]"
  echo "$0 [ start/stop [ ${clientList[*]} ]]"
  echo "$0 [ update [ ${clientList[*]} clientall | serverall | registry | config ]]"
  echo "The default param: status"
  exit 408
fi
echo "finished!"
