#!/bin/bash

# should upload to Octopus OSS

# Check if the correct number of arguments are provided
if [ "$#" -ne 3 ]; then
  echo "Usage: $0 <name_space> <deployment_name> <new_tag>"
  exit 1
fi

# Assign the arguments to variables
name_space=$1
deployment_name=$2
new_tag=$3

# echo "Name Space: $name_space Deployment Name: $deployment_name  New Tag: $new_tag"
# echo ""

deployment_image=$(kubectl -n "${name_space}" get deployment "${deployment_name}" -o=jsonpath='{.spec.template.spec.containers[*].image}')

old_tag=$(echo "${deployment_image}" | grep -oE ':[0-9]+\.[0-9]+\.[0-9]+.*')
image_prefix=${deployment_image%${old_tag}}
old_tag=${old_tag#*:}

# echo "old_tag is ${old_tag}"
# echo "image prefix is => ${image_prefix}"

kubectl -n "${name_space}" patch deployment "${deployment_name}" -p "{\"spec\":{\"template\":{\"spec\":{\"containers\":[{\"name\":\"${deployment_name}\",\"image\": \"${image_prefix}:${new_tag}\"}]}}}}" >>/dev/null

real_new_tag=$(kubectl -n "${name_space}" get deployment "${deployment_name}" -o=jsonpath='{.spec.template.spec.containers[*].image}' | grep -oE ':[0-9]+\.[0-9]+\.[0-9]+.*')
real_new_tag=${real_new_tag#*:}
current_date=$(date "+%Y-%m-%d-%H-%M-%S")

echo "${current_date} ${name_space} ${deployment_name} ${old_tag} ${real_new_tag}"
