#!/bin/bash
# Before running this script, you need to change `argocd-cm.yaml` to set `clientID` and `clientSecret`
# you can get it from configmap `argocd-cm` in namespace `argocd`

oldClientId=$(kubectl get -n argocd configmap argocd-cm -o jsonpath='{.data.dex\.config}' \
  | yq '.connectors[] | select(.id == "google") | .config.clientID')
oldClientSecret=$(kubectl get -n argocd configmap argocd-cm -o jsonpath='{.data.dex\.config}' \
  | yq '.connectors[] | select(.id == "google") | .config.clientSecret')
newClientId=$(yq '.data."dex.config"' argocd-cm.yaml \
  | yq '.connectors[] | select(.id == "google") | .config.clientID')
newClientSecret=$(yq '.data."dex.config"' argocd-cm.yaml \
  | yq '.connectors[] | select(.id == "google") | .config.clientSecret')

if [[ -z "$newClientId" || -z "$newClientSecret" ]]; then
  echo "Please set clientID and clientSecret in argocd-cm.yaml"
  exit 1
fi

if [[ -z "$oldClientId" || -z "$oldClientId" ]]; then
  echo "Please check kube context is correct"
  exit 1
fi

if [[ "$oldClientId" != "$newClientId" || "$oldClientSecret" != "$newClientSecret" ]]; then
  echo "ClientID or ClientSecret has changed, please update argocd-cm.yaml"
  exit 0
fi

date=$(date '+%Y%m%d')
kustomize build . --namespace=argocd > $date.yaml
echo "Generated manifest file: $date.yaml"
read -p "Are you sure to apply? [y/N]: " confirm
if [[ "$confirm" =~ ^[Yy]$ ]]; then
  echo "Confirmed."
else
  echo "Cancelled."
  exit 1
fi
kubectl apply -n argocd -f $date.yaml