#!/bin/bash
# 所有服务项目列表
GLOBAL_SERVICES=('central' 'route' 'logic' 'gateway' 'login' 'pay' 'fight' 'gm' 'chat')
# 查看所有服务
function WatchAllServices() {
  #ps -ef | grep $GLOBAL_SERVICE_NAME_PREFIX
  for globalServiceName1 in "${GLOBAL_SERVICES[@]}"; do
    echo $(ps -ef | grep "${GLOBAL_SERVICE_NAME_PREFIX}${globalServiceName1}")
  done
}

cwd=$(pwd)

echo "当前目录：${cwd}"

#启动的模块名
module=$1
#启动的模块id
id=$2
#单机模式
simple=''
#central用的参数
#central环境参数
env='dev'
#central启动模式
mode='a'
#其他模块使用
#启动的模块需要链接的central的ip
host='127.0.0.1'
#启动的模块需要链接的central的端口
port='6000'
centralIP='127.0.0.1'
moduleIP='127.0.0.1'
if [ "$module" = "central" ]; then
  env=$3
  mode=$4
  simple=$5
else
  host=$3
  port=$4
  env=$5
  centralIP=$6
  moduleIP=$7
fi

echo "module=$module"
echo "id=$id"
echo "env=$env"
echo "mode=$mode"
echo "host=$host"
echo "port=$port"

if [ "$module" = "central" ]; then
  echo 'Begin start central module...'
  echo $(pwd)
  echo $id
  echo $env
  echo $mode
  nohup central/central -i ${id} -e ${env} -m ${mode} -log_dir=log -alsologtostderr 2>&1 &
  sleep 2

  # central/central -i ${id} -e ${env} -m ${mode} -cpu central-cpu.prof -mem central-mem.prof 2>&1 &
  # 单机启动模式,就是在一台机器上启动所有的模块
  #if [ "$simple" = "" ]; then
    #startSingleService gm 900001
    #startSingleService login 800001
    #startSingleService pay 1000001
    #startSingleService version 1100001
    #startSingleService fight 400001
  #fi
  sleep 2
  echo "env=$env"
  # 查看所有进程
  WatchAllServices
  exit 0
elif [ "$module" = "gm" ]; then
  #startSingleService gm 900001
  exit 0
elif [ "$module" = "login" ]; then
  #startSingleService login 800001
  exit 0
elif [ "$module" = "pay" ]; then
  #startSingleService pay 1000001
  exit 0
elif [ "$module" = "version" ]; then
  #startSingleService version 1100001
  exit 0
elif [ "$module" = "fight" ]; then
  #startSingleService fight $id
  exit 0
elif [ "$module" = "route" ]; then
  nohup route/route -i ${id} -e ${env} -h ${host} -p ${port} -log_dir=log -alsologtostderr 2>&1 &
  #startSingleService fight $id
  exit 0
else
  echo "env=$env"
  cwd=$(pwd)
  echo $cwd
  echo "$module/${GLOBAL_SERVICE_NAME_PREFIX}$module -i $id -h $host -p $port"
  echo "moduleIp: $moduleIP centralIP: $centralIP"

  if [ "127.0.0.1" = "$moduleIP" ] || [ "$centralIP" = "$moduleIP" ]; then
    # echo "1111", $id >>${outfile}
    ${module}/${GLOBAL_SERVICE_NAME_PREFIX}${module} -i ${id} -e ${env} -h ${host} -p ${port} >> ${cwd}/logs/${module}_${id}.log 2>&1 &
    exit 0
  else
    echo "开始ssh...",$id
    myCmd="cd $cwd; bin/start_remote.sh $module $id $host $port $env ; exit"
    echo "remote ssh start sh: sh $moduleIP ", "$myCmd"
    # ssh -p 8022 $moduleIP "$myCmd"
    ssh $moduleIP > /dev/null 2>&1 "$myCmd"
  fi
  # ${module}/${module} -i ${id} -h ${host} -p ${port} -cpu ${module}-cpu.prof -mem ${module}-mem.prof 2>&1 &
fi

