#!/bin/bash
base_dir=/home/taxsys/
src_dir=${base_dir}"git_src/"
deploy_dir=${base_dir}
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=""



# 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 11
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 12
  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 13
    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 20
  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 21
  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 i in `ps -ef | grep ${user} | grep jar | egrep -e token-startup -e sign-startup -e user-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 149
  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_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 161
  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_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 tax-service-center-gateway;
    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" ]; then
             jvm_arg="-Xmx768M -Xms768M"
           else
             jvm_arg="-Xmx384M -Xms384M"
           fi
           nohup java ${jvm_arg} -jar ${deploy_dir}${cl_jar} ${start_para}>"${deploy_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_dir}${1}-startup.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 260
  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 sign-startup token-startup user-startup scan-startup taxfile-startup tax-service-center-gateway;
    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 "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 "source" | grep SNAPSHOT | egrep -e "startup" -e "gateway"`
    mc=${myclient##*/}
    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 -a $1 = "start" ]; then
  echo "Begin to start client(gateway/token/user/sign/scan/taxfile) ..."
  if [ $2 = "gateway" -o $2 = "token" -o $2 = "user" -o $2 = "sign" -o $2 = "scan" -o $2 = "taxfile" -o $2 = "all" ]; then
    start_client $2
  else
    echo "usage: start [gateway | token | user | sign | sign | taxfile | all ]"
    exit 309
  fi

elif [ $# = 2 -a $1 = "stop" ]; then
  if [ $2 = "gateway" -o $2 = "token" -o $2 = "user" -o $2 = "sign" -o $2 = "scan" -o $2 = "taxfile" -o $2 = "all" ]; then
    stop_client $2
  else
    echo "usage: stop [gateway | token | user | sign | scan | taxfile | all]"
    exit 317
  fi

elif [ $# = 1 -a $1 = "startall" ]; then
  echo "Begin to start all jars(server/config/gateway/token/user/sign/scan/file) ..."
  start_server
  start_client all

elif [ $# = 1 -a $1 = "stopall" ]; then
  echo "Begin to shutdown all jars(server/config/gateway/token/user/sign/scan/taxfile) ..."
  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 [ $2 = "gateway" -o $2 = "token" -o $2 = "user" -o $2 = "sign" -o $2 = "scan" -o $2 = "taxfile" -o $2 = "clientall" ]; then
    update_client $2
  else
    echo "usage: update [registry | config | gateway | token | user | sign | scan | taxfile | serverall | clientall]"
    exit 349
  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
else
  echo "Your param is wrong!"
  echo "usage:"
  echo "$0 [ startserver | stopserver | startall | stopall | force | status ]"
  echo "$0 [ start [gateway | token | user | sign | scan | taxfile] | stop [ gateway | token | user | sign | scan | taxfile ]]"
  echo "$0 [ update [gateway | token | user | sign | scan | taxfile | clientall | serverall | registry | config ]"
  echo "The default param: status"
  exit 361
fi
echo "finished!"
