#!/bin/bash

# @describe docker 中Local服务shell 菜单
# @usage TODO：看这里看这里 bin/xxxx_build_local.sh
# @author jiangpeng
# @param 参数说明
# $1 shell 指定cmdStr

# 引入全局文件
source $(pwd)/bin/global.sh

source /etc/profile

#ssh用户继承环境变量
#export $(cat /proc/1/environ |tr '\0' '\n' | xargs)

# 查看go是不是全局了
# go version

# docker 版本的，路径写死
# cd /home/slg/server/Trunk

# 调用的config目录，默认local
configPath=$SLG_TEST_ENV

fightHost=$SLG_FIGHT_HOST
if [ -z "$fightHost" ]; then
  fightHost=192.168.7.248 #加一个 elif 或者直接在这里修改，SVN不提交就可以了
fi

echo "fightHost is $fightHost"

# 动态生成配置文件
myEnv=${SLG_TEST_ENV}
if [ ${myEnv} != "local" ]; then
    echo "当前程序路径：${SLG_TEST_CODE_PATH} 构建配置文件目录：${myEnv}"
    oldPwd=$(pwd)
    cd /home/slg/server/Trunk
    rm -rf config/${myEnv}
    cp -r config/local config/${myEnv} #cp新目录
    echo "开始替换redis host"
    find config/${myEnv} -name '*.json' -print0 | xargs -0 perl -pi -e "s/slg-redis/slg-redis${SLG_TEST_APP_SUFFIX}/g"
    echo "开始替换mysql host"
    find config/${myEnv} -name '*.json' -print0 | xargs -0 perl -pi -e "s/slg-mysql/slg-mysql${SLG_TEST_APP_SUFFIX}/g"
    cd ${oldPwd}
fi

function buildLocal() {
  bash bin/build.sh local "${1}" "${2}"
}

# dlv 启动服务
function startDlv() {

  #这里是无序的没办法
  declare -A dlvServices=(["central"]=44400 ["gateway"]=44401 ["world"]=44402 ["logic"]=44403 ["mapsearch"]=44404 ["chat"]=44405 ["fight"]=44406 ["gm"]=44407 ["login"]=44408 ["report2"]=44409 ["report"]=44410 ["pay"]=44409)

  #指定启动程序
  index=$(expr "$1" - 700)

  # 重新编译所有程序
  #  if [ $index -lt 0 ]; then
  #    buildLocal
  #  fi

  for serviceName in ${GLOBAL_SERVICES[@]}; do
    if [ $index -ge 0 ] && [ ${GLOBAL_SERVICES[$index]} != $serviceName ]; then
      continue
    fi

    # dlv 端口
    listenPort=${dlvServices[$serviceName]}

    # 前缀+应用名
    appName=${GLOBAL_SERVICE_NAME_PREFIX}${serviceName}
    printf "%s\t%s\n" "${listenPort}" "${appName}"

    # 删除之前log
    if [ -f "logs/dlv/${appName}.log" ]; then
      rm -f logs/dlv/"${appName}".log
    fi

    mkdir -p logs/dlv/ && touch logs/dlv/${appName}.log && chmod 0777 logs/dlv/${appName}.log

    args=''
    if [ "${serviceName}" = "central" ] || [ "${serviceName}" = "gm" ] || [ "${serviceName}" = "login" ]  || [ "${serviceName}" = "pay" ]; then
      args=' -- --e='$configPath
    fi

    # 重新编译 -- 指定编译
    # shellcheck disable=SC2086
    if [ $index -ge 0 ]; then
      buildLocal ${serviceName} "noPackage"
    fi

    # 杀死这个进程
    KillForceAllService 9 ${serviceName}

    # 启动dlv
    bin/tool/dlv --listen=:${listenPort} --headless=true --api-version=2 --accept-multiclient exec ${serviceName}/${appName} ${args} >>logs/dlv/${appName}.log 2>&1 &

  done

  # 休息一下
  sleep 1
}

function tailBenchmark() {
  tail -f benchmark/logs/*/*.log | grep "$1"
}

function printErrTip() {
    echo -e "\033[31m Please check what you input ! \033[0m"
}

# 通过shell 参数直接重启DLV
function startWithShellArg() {
  # 1. 杀掉所有进程
  echo '开始kill所有进程：'
  KillForceAllService
  sleep 1
  KillForceAllService
  echo 'kill以后：查看进程'
  WatchAllServices

  # 2. Dlv启动进程
  echo '开始启动所有进程Dlv版本：'
  startDlv $1

  # 3.查看所有进程
  echo 'startDlv以后：查看进程'
  WatchAllServices
}

######function define
function acceptCmd() {

  echo -e "\033[33m
 请输入你的Local命令：
 1. build
 2. start
 3. stop
 4. lazy（一键停止、编译、启动）[40: 停止，编译并启动 41：一键重启（不编译）]
 5. client
 6. fight - connect your windows host fight
 7. dlv [7:'all' 700:'central' 701:'gateway' 702:'world' 703:'logic' 704:'mapsearch' 705:'chat' 706:'fight' 707:'gm' 708:'login' 709:'pay' 710:'report']
 8. watch all progress
 9. tailBenchmark [9:'exec 当前正在执行任务' 91:'用户执行任务情况']
 10.mysql-client
 11. 安装ssh [110: 安装并启动sshd 1111: 设置ssh root密码]
 12. 服务器状态14：恢复 [120: 蒋鹏稳定 121: 蒋鹏开发]
 \033[0m"

  # shellcheck disable=SC2162
  if read -p "please input：" cmdStr; then
    if [[ $cmdStr == [1] ]]; then
      buildLocal
      acceptCmd # 重启菜单面板
    elif [[ $cmdStr == [2] ]]; then
      bash bin/start.sh central 100001 $configPath a
       acceptCmd # 重启菜单面板
    elif [[ $cmdStr == [3] ]]; then
      # bash bin/stop.sh central
      # 停止所有服务
      KillForceAllService
      # 查看服务
      WatchAllServices
      acceptCmd # 重启菜单面板
    elif [[ $cmdStr == 4* ]]; then
       #1. 停止所有服务
      KillForceAllService
      if [ "$cmdStr" = '40' ]; then
        #2. 编译程序
        buildLocal
      fi
      #3. 开启服务
      bash bin/start.sh central 100001 $configPath a
      acceptCmd # 重启菜单面板
    elif [[ $cmdStr == [5] ]]; then
      cd client/ && go build && cd .. && client/client
    elif [[ $cmdStr == [6] ]]; then
      fight/fight -i 400001 -h $fightHost -p 6000
    elif [[ $cmdStr == 7* ]]; then
      # go install github.com/go-delve/delve/cmd/dlv #安装dlv cmd
      startDlv $cmdStr
      acceptCmd # 重启菜单面板
    elif [[ $cmdStr == [8] ]]; then
      # 查看所有进程
      WatchAllServices
      acceptCmd # 重启菜单面板
    elif [[ $cmdStr == 9* ]]; then
      if [ "$cmdStr" = '9' ]; then
        tailBenchmark "exec 当前正在执行任务"
      elif [ "$cmdStr" = '91' ]; then
        tailBenchmark "用户执行任务情况"
      fi
    elif (( "$cmdStr" == "10" )); then
      # 安装mysql-cli
      yum install -y mysql
      # 链接集群中mysql
      echo -e "\033[34m set names utf8;\033[0m"
      echo "source `pwd`/sql/"
      echo -e "\033[34m connecting to mysql cmd: mysql -hslg-mysql${SLG_TEST_APP_SUFFIX} -uroot -p\033[0m"
      mysql -hslg-mysql${SLG_TEST_APP_SUFFIX} -uroot -p123456
    elif [[ $cmdStr == 11* ]]; then
      if [ "$cmdStr" = '110' ]; then
          echo "安装并启动sshd"
          yum install openssh-server -y
          /sbin/sshd
          acceptCmd # 重启菜单面板
      elif [ "$cmdStr" = '111' ]; then
          echo "安装passwd"
          yum install passwd -y
          echo "设置密码："
          passwd
          acceptCmd # 重启菜单面板
      fi
     elif [[ $cmdStr == 12* ]]; then
        yum install -y curl
        #TODO: 参数化，或者scan化
         if [ "$cmdStr" = '120' ]; then
            gmHost='192.168.7.248:22000'
         elif [ "$cmdStr" = '121' ]; then
            gmHost='192.168.7.248:12000'
         fi
         echo "----host---:$gmHost"
         curl --location "$gmHost/cmd" --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'cmd=3' --data-urlencode 'payload={"Optype":7,"ServerIDs":[1]}'
         acceptCmd # 重启菜单面板
    else
      [[ $cmdStr != [33333] ]]
      printErrTip
    fi
  else
    printErrTip
  fi
}

# 通过shell指定启动命令, 不用启动菜单了
cmdStrShell=$1
if [ "${cmdStrShell}" != "" ]; then
  # 写死吧，防止误操作，指定 7 重启所有
  startWithShellArg 7
  exit 1
fi

# 启动菜单
acceptCmd
