#!/bin/bash


full_image_name_list_path=/root/octopus_image/cmii/all-cmii-image-list.txt
name_space=xmyd
local_harbor_prefix=192.168.0.8:8033/cmii

read_and_update_cmii_image_tag(){
  linux_images=()
  while IFS= read -r i; do
      [ -z "${i}" ] && continue
      linux_images+=("${i}");
  done < "${full_image_name_list_path}"

  for i in "${linux_images[@]}"; do
      [ -z "${i}" ] && continue
      echo ""
      echo "[update] -- start of ${i}"
      case $i in
      */*/*)
          last_segment="${i##*/}"
          local app_name=$(echo $last_segment | cut -d":" -f1)
          local new_tag=$(echo $last_segment | cut -d":" -f2)
          local image_name="$local_harbor_prefix/$app_name"
          echo "[update] -- app of ${app_name} to ${new_tag}  ==> $image_name:${new_tag}"

          if kubectl get deployment ${app_name} -n ${name_space} --ignore-not-found; then
              echo "Deployment exists"
              kubectl -n ${name_space} patch deployment ${app_name} -p "{\"spec\":{\"template\":{\"spec\":{\"containers\":[{\"name\":\"${app_name}\",\"image\": \"${image_name}:${new_tag}\"}]}}}}"
          else
              echo "Deployment does not exist of ${app_name}"
          fi
          ;;
      *)
          image_name="${DockerRegisterDomain}/rancher/${i}"
          ;;
      esac
  done
}

read_and_update_cmii_image_tag