#!/bin/bash

#记录开始时间
startTime=$(date +%s)

# 登录到目标环境
baseDir="/home/somuns/ci4s"
cd ${baseDir}


#build
# 默认参数
branch="master"
service="manage-front"
env="dev"

#
show_help() {
  echo "Usage: $0 [-b branch] [-s service] [-e environment]"
  echo
  echo "Options:"
  echo "  -b  Branch to deploy, default: master"
  echo "  -s  Service to deploy (manage-front, manage, front, all, default: manage-front)"
  echo "  -e  Environment (e.g., dev, test, default: dev)"
  echo "  -h  Show this help message"
}

# 解析命令行选项
while getopts "b:s:e:h" opt; do
  case $opt in
    b) branch=$OPTARG ;;
    s) service=$OPTARG ;;
    e) env=$OPTARG ;;
    h) show_help; exit 0 ;;
    \?) echo "Invalid option -$OPTARG" >&2; show_help; exit 1 ;;
  esac
done

valid_services=("manage-front" "manage" "front" "all")
if [[ ! " ${valid_services[@]} " =~ " $service " ]]; then
  echo "Invalid service name: $service" >&2
  echo "Valid services are: ${valid_services[*]}"
  exit 1
fi

valid_envs=("dev" "test")
if [[ ! " ${valid_envs[@]} " =~ " $env " ]]; then
  echo "Invalid environment: $env" >&2
  echo "Valid environments are: ${valid_envs[*]}"
  exit 1
fi

echo "start build"
sh ${baseDir}/k8s/build.sh -b ${branch} -s ${service}
if [ $? -ne 0 ]; then
  echo "Build failed"
  exit 1
fi
echo "build success"

# 部署
echo "start deploy"
sh ${baseDir}/k8s/deploy.sh -s ${service} -e ${env}
if [ $? -ne 0 ]; then
  echo "Deploy failed"
  exit 1
fi
echo "deploy success"

# 记录结束时间
endTime=$(date +%s)
# 计算运行时间
duration=$(( $endTime - $startTime ))
echo "编译发布总耗时: $duration 秒"