#!/bin/bash
CUSTOMER="${1}"
ENVIRONMENT="${2}"

usage() {
  echo "Usage: ${0} <customer> <environment> [target revison]"
  echo "Example: ${0} nordunet test"
  echo "Example: ${0} nordunet test k8s-manifests-2023-09-27-v01"
  exit 0
}

if [[ -z ${CUSTOMER} ]] || [[ -z ${ENVIRONMENT} ]]; then
  usage
fi

if [[ -n ${3} ]]; then
  TAG="${3}"
  if ! git tag -l | grep "${TAG}"; then
    echo "${TAG} is not a valid tag"
    usage
  fi
else
  TAG="$(git tag -l | tail -1)"
fi
if [[ "${ENVIRONMENT}" != 'test' ]] && [[ "${ENVIRONMENT}" != 'prod' ]]; then
  echo "${ENVIRONMENT} is not a valid environment (should be test or prod)"
  usage
fi

ARGOCD="argocd.drive.test.sunet.se"
if [[ "${ENVIRONMENT}" == 'prod' ]]; then
  ARGOCD="argocd.drive.sunet.se"
fi

JSON='[{"op": "replace", "path": "/spec/source/targetRevision", "value": "'${TAG}'"}]'

PASSWORD="$(pass show ${ARGOCD}/admin)"
if [[ -z ${PASSWORD} ]]; then
  echo "Make sure you have the 'pass' program installed and the argocd password available with \`pass show ${ARGOCD}/admin\`"
fi

argocd --grpc-web --kube-context "drive-${ENVIRONMENT}" login --username admin --password "${PASSWORD}" "${ARGOCD}"
argocd --kube-context "drive-${ENVIRONMENT}" app patch "${CUSTOMER}" --patch "${JSON}"
argocd --kube-context "drive-${ENVIRONMENT}" app sync "${CUSTOMER}" --revision "${TAG}"
