#!/bin/bash
set -euo pipefail

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
TEST_ID=$(uuidgen | cut -d'-' -f1 | tr '[:upper:]' '[:lower:]')
TMP_DIR=$SCRIPTPATH/../../build/helm-sync-$TEST_ID
GITHUB_CURL_AUTH=""
if [[ ! -z $GITHUB_TOKEN ]]; then
    GITHUB_CURL_AUTH="-u $GITHUB_TOKEN:x-oauth-basic"
fi

mkdir -p $TMP_DIR
cd $TMP_DIR

prs=$(curl -s $GITHUB_CURL_AUTH https://api.github.com/repos/aws/eks-charts/pulls)

branches=()
while IFS='' read -r line; do 
   branches+=("$line"); 
done < <(echo $prs | jq -r '.[].head.ref')

clone_urls=()
while IFS='' read -r line; do 
   clone_urls+=("$line"); 
done < <(echo $prs | jq -r '.[].head.repo.clone_url')

branches+=("master")
clone_urls+=("https://github.com/aws/eks-charts.git")

for i in "${!branches[@]}"; do
    git clone --branch "${branches[$i]}" "${clone_urls[$i]}" $TMP_DIR/pr$i || continue
    if [[ ! -d $TMP_DIR/pr$i/stable/aws-node-termination-handler ]]; then
       continue
    fi
    diff -r $TMP_DIR/pr$i/stable/aws-node-termination-handler $SCRIPTPATH/../../config/helm/aws-node-termination-handler | tee $TMP_DIR/chart-diff-pr$i.txt || continue
   
    if [[ $i -eq 0 ]]; then
        echo "✅ AWS Node Termination Handler helm chart is in-sync with the eks-charts repo!"
    else
        echo "✅ AWS Node Termination Handler helm chart is in-sync with a PR (${clone_urls[$i]} -branch ${branches[$i]}) in eks-charts repo!"
    fi
    exit 0
done

echo "❌ The Helm chart is NOT in-sync with the eks-charts repo. Please submit a PR to eks-charts via 'make ekscharts-sync' before merging this code."
echo "Check $TMP_DIR for more details"

exit 1
