#!/bin/bash
cmd=$1

# 清除release镜像版本
function clear_release_image() {
  release_image_version=`$image_version`"_beta"
  docker images | grep $release_image_version > /dev/null 2>&1 && docker images | grep none|awk '{print $3 }' | xargs docker rmi
  echo "成功清除release版本"$release_image_version
}
# 规范镜像版本
function foramt_image_version() {
  release_reg='^release\/.*$'
  if [[ "$CI_COMMIT_REF_NAME" =~  $release_reg ]]; then
    image_version="v"`echo $CI_COMMIT_REF_NAME | grep -Eo '[0-9]+.[0-9]+'`"_beta"
  elif [ "$CI_COMMIT_REF_NAME" == "dev" ]; then
    image_version=$CI_COMMIT_REF_NAME
  else
    image_version="v"`echo $CI_COMMIT_REF_NAME | grep -Eo '[0-9]+.[0-9]+'`
  fi
  echo "版本:"$CI_COMMIT_REF_NAME"成功修正为:"$image_version
}
# 写入版本号
function log_version() {
  now_time=`date +%Y%m%d_%H%M%S`
  echo time: $now_time > version.txt
  echo branch: ${CI_COMMIT_REF_NAME} >> version.txt
}
# 构建docker镜像
function build_docker_image() {
  log_version
  foramt_image_version
  docker build -t ${APP_IMAGE}:$image_version .
  # 正式版本构建后，清除release版本
  tags_reg='^[0-9]+.[0-9]+.[0-9]+$'
  if [[ "$CI_COMMIT_REF_NAME" =~ $tags_reg ]]; then
    echo "开始清理release镜像"
    clear_release_image
  fi
}
# 主流程
if [ -z "$cmd" ]; then
  echo "命令不能为空"
  exit 0
elif [ "$cmd" == "build" ]; then
  echo "build..."
  build_docker_image
elif [ "$cmd" == "push" ]; then
  echo "push..."
  foramt_image_version
  docker push ${APP_IMAGE}:$image_version
elif [ "$cmd" == "push_ali" ]; then
  echo "push_ali..."
  foramt_image_version
  docker tag ${APP_IMAGE}:$image_version ${ALI_IMAGE}:${CI_COMMIT_REF_NAME}
  docker push ${ALI_IMAGE}:$image_version
else
  echo "无效命令:$cmd"
  exit 0
fi