#!/bin/bash

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=($(echo $prs | jq -r '.[].head.ref'))
clone_urls=($(echo $prs | jq -r '.[].head.repo.clone_url'))

branches=("master" "${branches[@]}")
clone_urls=("https://github.com/aws/eks-charts.git" "${clone_urls[@]}")

for i in "${!branches[@]}"; do
    git clone --branch "${branches[$i]}" "${clone_urls[$i]}" $TMP_DIR/pr$i
    DIFF_OUTPUT=$(diff -r $TMP_DIR/pr$i/stable/aws-node-termination-handler $SCRIPTPATH/../../config/helm/aws-node-termination-handler)
    DIFF_ECODE=$?
    echo "$DIFF_OUTPUT" > $TMP_DIR/chart-diff-pr$i.txt

    if [[ $DIFF_ECODE -eq 0 ]]; then
        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
    else 
        echo "===================================== DIFF ========================================================"
        echo "${clone_urls[$i]} -branch ${branches[$i]}"
        echo "$DIFF_OUTPUT"
        echo "===================================== END DIFF ===================================================="
    fi 
done

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

exit 1
