#!/bin/bash

# This shell is executed before docker build.

# 运行时候后面加入 -c 选项，-c后可设置安装多个镜像
while getopts "c:" opt; do
  case $opt in
  c)
    # 根据编号跟具体镜像名称匹配
    case $OPTARG in
    1)
      repository="kami_frontend"
      ;;
    2)
      repository="kami_backend"
      ;;
    3)
      repository="kami_boss"
      ;;
    4)
      repository="kami_merchant"
      ;;
    5)
      repository="kami_shop"
      ;;
    6)
      repository="kami_gateway"
      ;;
    7)
      repository="kami_agent"
      ;;
    *)
      echo "Invalid option: -$OPTARG" >&2
      help
      exit 1
      ;;
    esac
    install repository
    ;;
  \?)
    echo "Invalid option: -$OPTARG" >&2

    help
    exit 1
    ;;
  esac
done

help() {
  echo 1. kami_frontend
  echo 2. kami_backend
  echo 3. kami_boss
  echo 4. kami_merchant
  echo 5. kami_shop
  echo 6. kami_gateway
  echo 7. kami_agent
}

install() {
  $repository = $1

  # 如果当前文件夹不存在，拉取资源
  if [ ! -d $repository ]; then
    echo "克隆代码..."
    git clone git@121.37.253.228:sunxiaolong/$repository.git
  fi

  cd $repository
  git checkout master
  git pull

  # 如果当前容器存在，则停止并删除
  if [ "$(docker ps -a | grep $repository)" ]; then
    echo "停止并删除容器..." $repository
    docker stop $repository && docker rm $repository
  fi

  # 关掉docker中所有其他的容器
  echo "关掉docker中所有其他的容器..."
  # shellcheck disable=SC2046
  docker stop $(docker ps -a -q)
  # 构建并启动docker容器
  echo "构建并启动docker容器..."

  if [ $repository == "kami_frontend" ]; then
    echo "构建并启动docker容器..."
    docker compose -f ./deploy/docker-compose.yml up -d --build
  elif [ $repository == "kami_backend" ]; then
    echo "构建并启动docker容器..."
    docker compose -f ./manifest/docker/docker-compose.yml up -d --build
  else
    docker compose -f docker-compose.yaml up -d --build
    # 开启docker所有的容器
  fi

  if [ -d "$repository" ]; then
    echo "删除本地代码..."
    rm -rf $repository
  fi
  # 查找悬空的（无标签的）镜像
}

echo
echo "开启docker所有的容器..."
# shellcheck disable=SC2046
docker start $(docker ps -a -q)
# 删除本地代码
cd ..

# 暂停10s
for i in {10..1}; do
  echo -ne "暂时等待..$i \r"
  sleep 1
done

# 重启以kami_开头的所有容器
echo "重启以kami_开头的所有容器..."
# shellcheck disable=SC2046
docker restart $(docker ps -a | grep kami_ | awk '{print $1}')

# 删除悬空的镜像
# shellcheck disable=SC2046
# 如果有悬空镜像，就删除
if [ "$(docker images -f "dangling=true" -q)" ]; then
  echo "删除悬空的镜像..."
  docker rmi $(docker images -f "dangling=true" -q)
fi

# 自我删除
if [ -f "./install.sh" ]; then
  echo "自我删除..."
  rm -rf ./install.sh
fi
