#!/usr/bin/env bash

echo "$1"
echo "$2"
echo "$3"
echo "$4"

export SERVICE_NAME="$3"
export IMAGE_TAG="$4"

mkdir -p /host/.kube
base64 < config -d > /host/.kube/config
export KUBECONFIG=/host/.kube/config

if [ "$1" = "apply" ];then
  kubectl delete configmap "$3"-config -n "$2" || true
  kubectl create configmap "$3"-config --from-file="$3".toml -n "$2"

  if  ./replace.sh deployment.yaml | kubectl apply -n  "$2" -f - | grep -q unchanged; then
      echo "=> Patching deployment to force image update."
      ./replace.sh deployment.yaml | kubectl patch -p "{\"spec\":{\"template\":{\"metadata\":{\"annotations\":{\"ci-last-updated\":\"$(date +'%s')\"}}}}}" -n "$2" -f -
  else
      echo "=> Deployment apply has changed the object, no need to force image update."
  fi
  ./replace.sh service.yaml | kubectl "$1" -n "$2" -f - || true
  ./replace.sh deployment.yaml | kubectl rollout status -n "$2" -f -
else
  ./replace.sh service.yaml | kubectl "$1" -n "$2" -f - || true
  ./replace.sh deployment.yaml | kubectl "$1" -n "$2" -f - || true
fi
