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

usage(){
  echo "migrate and start server script"
  echo "sh startA.sh install|pull|changeIp|showIp|db|app|usage"
}

dockerInstall(){
	nohup docker --version >/dev/null 2>&1  &
	if [ $? -ne 0 ]; then
		echo "docker not install, please install docker"
		sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["http://hub-mirror.c.163.com", "https://docker.mirrors.ustc.edu.cn" ],
  "insecure-registries": ["192.168.50.103:8000", "192.168.50.108:8000" ]
}
EOF
    curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
    ln -sf /usr/libexec/docker/cli-plugins/docker-compose /usr/local/bin/docker-compose
  else
    echo "docker already install"
	fi
}

getPrivateIP(){
  local interIP=$(ip addr|grep global |grep eth0 |awk '{print $2}'| awk -F '/' '{print $1}')
  echo "$interIP";
}

getPublicIP(){
  publicIp=`curl -s http://members.3322.org/dyndns/getip`;
  echo "$publicIp";
}

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

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

changeIP(){
  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
}

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


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

images=(redis:7.2.4
redis:6.2.1
openjdk:11-jdk
nacos/nacos-server:v2.3.2
nacos/nacos-mysql:5.7
adminer:latest
postgres:13
nginx:1.21-alpine
lscr.io/linuxserver/openssh-server:latest
foxiswho/rocketmq:4.8.0
styletang/rocketmq-console-ng:latest
docker.elastic.co/elasticsearch/elasticsearch:7.10.2
)
imagePull(){
	for image in "${images[@]}";do
	  echo "pull image $image"
	  nohup docker pull $image >>offlineImage.log 2>&1  &
	done
}

start1(){
 dir=$1
 echo "start $dir..."
 if [ -d $dir ];then
   cd $dir
#   nohup docker-compose up -d >/dev/null 2>&1  &
   docker-compose up -d
   cd ../
 fi
}

start2(){
 dir=$1
 echo "start ${pwd}/${dir}..."
 if [ -d "$dir" ];then
    init_dir=$(pwd)
    cd "${dir}"
    echo "parent_dir: ${parent_dir}"
    docker-compose build
    docker-compose down
#    nohup docker-compose up -d >/dev/null 2>&1  &
    docker-compose up -d
    cd "${init_dir}"
 fi
}

start3(){
  echo "start rocketmq"
  if [ -f "rocketmq/rmq/start.sh" ];then
    cd rocketmq/rmq
    ./start.sh
    cd ../../
  fi
}


## start middleware
startmiddleware(){
	start1 elasticsearch
	start1 nacos
	start1 postgresql
	start1 redis
	start1 sftp
	start3 rocketmq
}

## start app
startApp(){
	start2 apps/platform-mgnt-service
	start2 apps/asset-mgnt-service
	start2 apps/auth-service
	start2 apps/common-gateway
	start2 apps/ea-flowable
	start2 apps/ea-vue3
}

## clean
middleware=(
  ea_sftp
  ea_rmqconsole
  ea_rmqbroker
  ea_rmqnamesrv
  ea_redis
  ea_postgresql
  ea_postgresql_adminer
  ea_nacos2
  ea_nacos2_mysql
  ea_es
)
apps=(
  ea_platform
  ea_vue3
  ea_ui
  ea_flowable
  ea_gateway
  ea_auth
  ea_asset
)
# 显示 应用状态
status(){
  for app in "${apps[@]}";do
    flag=$(docker ps -a | grep -q "${app}" && echo "found")
    if [[ -z "$flag" ]];then
      echo "----------------------------------------"
      echo "app $app start fail."
      echo "----------------------------------------"
    fi
  done
  for m in "${middleware[@]}";do
      flag=$(docker ps -a | grep -q "${m}" && echo "found")
      if [[ -z "$flag" ]];then
        echo "----------------------------------------"
        echo "middleware $m start fail."
        echo "----------------------------------------"
      fi
    done
}

## print Container Name
printContainer(){
  docker ps --format "{{.ID}}\t{{.Names}}"
}


# startmiddleware
# startApp


createNetwork(){
  echo "create new work"
  retVal=$(docker network ls | grep ea_net)
  if [ -n "$retVal" ];then
    echo "create network success!"
  else
    echo "create network already exists!"
    docker network create ea_net;
  fi
}

# stop
stop(){
  docker stop $(docker ps -a | grep -v "CONTAINER ID" | awk '{print $1}')
  docker rm $(docker ps -a | grep -v "CONTAINER ID" | awk '{print $1}')
}

all(){
  echo "1. install docker"
  dockerInstall
  echo "2. change config Ip"
  showIp
  changeServer
  echo "3. pull image"
  imagePull
  echo "4. start middleware"
  startmiddleware
  echo "5. start app"
  startApp
  echo "6. check status"
  status
}

if [ $# -eq 0 ];then
    dockerInstall
else
    case "$1" in
      "install")
            dockerInstall
         ;;
      "changeIp")
          changeServer
        ;;
      "showIp")
        showIp
      ;;
      "pull")
          imagePull
      ;;
      "status")
        status
      ;;
    "container")
        printContainer
      ;;
     "network")
        createNetwork
      ;;
      "stop")
        stop
      ;;
		  "app")
        startApp
      ;;
		  "db")
        startmiddleware
      ;;
      "all")
          all
        ;;
      *)
          usage
      ;;
    esac
fi
