#!/bin/sh
work_dir=$(cd `dirname $0`;pwd)

usage(){
  echo "Usage: This Migrate Server Change apps,apps2,rocketmq NACOS_SERVER IP and RocketMQ server IP,  "
  echo "Usage: ./migrate.sh showIp|changeIp|"

}
getPrivateIP(){
  local interIP=`ip addr|grep global |grep eth0 |awk '{print $2}'| awk -F '/' '{print $1}'`
  echo "$interIP";
}
getPublicIP(){
  local publicIp=$(curl -s http://members.3322.org/dyndns/getip)
  echo "$publicIp";
}

getOldIp(){
  local oldIP=`cat apps/env/app.env|grep "NACOS_SERVER" |awk -F "=" '{print $2}'`
  echo "$oldIP";
}

replace(){
  local oldIp=$1
  local newIp=$2
  local file=$3
  sed -i "s/$oldIp/$newIp/g" $file
}

changeIP(){
  #  grep $beforeIp -rl * | while read line; do echo "替换的文件：$line，beforeIp: $beforeIp, afterIP: $afterIP"; sed -i "s/$beforeIp/$afterIP/g" $line ;done;
  #  echo "替换完成后结果"
  #  grep $beforeIp -rl *
  #  cd ../
  local dirName=$1
  local beforeIp=$2
  local afterIP=$3
  echo " 替换 $dirName 目录下文件 IP $beforeIp -> $afterIP"
  if [ -d $dirName ];then
    cd $dirName
    grep $beforeIp -rl * | while read line; do echo "替换的文件：$line，beforeIp: $beforeIp, afterIP: $afterIP"; sed -i "s/$beforeIp/$afterIP/g" $line ;done;
    echo "替换完成后结果 "
    grep $beforeIp -rl *
    cd $work_dir
  fi
}

migrate(){
  beforeIp="$(getOldIp)"
  afterIP="$(getPrivateIP)"
  echo " 替换 Apps 目录下文件 IP"
  changeIP apps $beforeIp $afterIP
  echo " 替换 Apps2 目录下文件 IP"
  changeIP apps2 $beforeIp $afterIP
  echo " 替换 rocketmq 目录下文件"
  changeIP rocketmq $beforeIp $afterIP
}


showIp(){
  beforeIp="$(getOldIp)"
  afterIP="$(getPrivateIP)"
  publicIp="$(getPublicIP)"
  echo " 替换 Apps2 目录下文件 beforeIp: $beforeIp, afterIP: $afterIP, publicIp: $publicIp"
}

if [ $# -eq 0 ];then
    usage
else
    case "$1" in
        "changeIp")
            migrate
         ;;
        "showIp")
            showIp
          ;;
       "usage")
          usage
        ;;
        *)
            usage
        ;;
    esac
fi