#!/bin/bash

harbor_host=10.40.51.5:8033
namespace=jsntejpt
app_name=""
new_tag=""

upload_image_to_harbor(){
   if [ "$app_name" == "" ]; then
       echo "app name null exit!"
       exit 233
   fi

   if ! docker load < "$1"; then
       echo "docker load error !"
   fi
   docker tag "harbor.cdcyy.com.cn/cmii/$app_name:$new_tag" "$harbor_host/cmii/$app_name:$new_tag"
   echo ""
   echo ""
   echo "upload_image_to_harbor - start to push to => $harbor_host/cmii/$app_name:$new_tag"
   docker login -u admin -p V2ryStr@ngPss $harbor_host
   docker push "$harbor_host/cmii/$app_name:$new_tag"
   echo ""
   echo ""

}

parse_args(){
  if [ "$1" == "" ]; then
      echo "no zip file in error!"
      exit 233
  fi
  local image_name="$1"

  # cmii-uav-surveillance=5.2.0-27031-cqga=2024-03-04=573.tar.gz
   app_name=$(echo $image_name | cut -d "=" -f1)
   new_tag=$(echo $image_name | cut -d "=" -f2)
}

update_image_tag(){
  if [ "$new_tag" == "" ]; then
      echo "new tag error!"
      exit 233
  fi

   local image_prefix=$(kubectl -n ${namespace} get deployment "${app_name}" -o=jsonpath='{.spec.template.spec.containers[*].image}' | cut -d":" -f1)

    echo "image grep is => ${image_prefix}"

    echo "start to update ${namespace} ${app_name} to ${new_tag} !"
    echo ""
    kubectl -n ${namespace} patch deployment "${app_name}" -p "{\"spec\":{\"template\":{\"spec\":{\"containers\":[{\"name\":\"${app_name}\",\"image\": \"${harbor_host}/cmii/$app_name:${new_tag}\"}]}}}}"
    echo ""
    echo "start to wait for 3 seconds!"
    sleep 3
    local image_new=$(kubectl -n ${namespace} get deployment "${app_name}" -o=jsonpath='{.spec.template.spec.containers[*].image}')
    echo ""
    echo "new image are => $image_new"
    echo ""
}

main(){
   parse_args "$1"
   upload_image_to_harbor "$1"
   update_image_tag
}

main "$@"