#!/bin/bash

set -e

dir=${PWD##*/}

gradle assemble

# Get the current Git branch
branch=$(git rev-parse --abbrev-ref HEAD)

# Replace any slashes (e.g., in 'feature/' or 'release/') with a hyphen
cleaned_branch=$(echo "$branch" | sed 's/\//_/g')

# Get the short commit hash (first 5 characters)
commit_hash=$(git rev-parse --short=5 HEAD)

# Combine branch and commit hash
buildName="${USER}-${cleaned_branch}-${commit_hash}"

gradle bootBuildImage --publishImage -PbuildbootDockerHostNetwork=true -Pversion=${buildName}

newImageName="nexus.knecon.com:5001/red/${dir}-server-v1:${buildName}"

echo "full image name:"
echo ${newImageName}
echo ""

if [ -z "$1" ]; then
    exit 0
fi

namespace=${1}
deployment_name="persistence-service-v1"

echo "deploying to ${namespace}"

oldImageName=$(rancher kubectl -n ${namespace} get deployment ${deployment_name} -o=jsonpath='{.spec.template.spec.containers[*].image}')

if [ "${newImageName}" = "${oldImageName}" ]; then
    echo "Image tag did not change, redeploying..."
    rancher kubectl rollout restart deployment ${deployment_name} -n ${namespace}
else
    echo "upgrading the image tag..."
    rancher kubectl set image deployment/${deployment_name} ${deployment_name}=${newImageName} -n ${namespace}
fi
rancher kubectl rollout status deployment ${deployment_name} -n ${namespace}
echo "Built ${deployment_name}:${buildName} and deployed to ${namespace}"
