#!/bin/bash


    set -o nounset   # disallow usage of unset vars  ( set -u )
    set -o errexit   # Exit immediately if a pipeline returns non-zero.  ( set -e )
    set -o errtrace  # Allow the above trap be inherited by all functions in the script.  ( set -E )
    set -o pipefail  # Return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status
    IFS=$'\n\t'      # Set $IFS to only newline and tab.



dir="/tmp/mongo_repo_$( uuidgen )"

echo ""
echo "> Clone https://github.dev/mongodb/mongo-go-driver"
echo ""

git clone "https://github.com/mongodb/mongo-go-driver" "$dir"

pushd "$dir"

git fetch --tags

latestTag="$( git describe --tags `git rev-list --tags --max-count=1` )"

git -c "advice.detachedHead=false" checkout $latestTag

latestSHA="$( git rev-parse HEAD )"

popd

existingTag=$( cat mongoPatchVersion.go | grep -oP "(?<=const MongoCloneTag = \")([A-Za-z0-9.]+)(?=\")" )
existingSHA=$( cat mongoPatchVersion.go | grep -oP "(?<=const MongoCloneCommit = \")([A-Za-z0-9.]+)(?=\")" )

echo "===================================="
echo "ID  (online) $latestSHA"
echo "ID  (local)  $existingSHA"
echo "Tag (online) $latestTag"
echo "Tag (local)  $existingTag"
echo "===================================="

if [[ "$latestTag" == "$existingTag" ]]; then
  echo "Nothing to do"
  rm -rf "$dir"
  exit 0
fi

echo ""
echo "> Copy repository"
echo ""

rm -rf mongo
cp -r "$dir" "mongo"
rm -rf "$dir"

echo ""
echo "> Clean repository"
echo ""

rm -rf "mongo/.git"
rm -rf "mongo/.evergreen"
rm -rf "mongo/cmd"
rm -rf "mongo/docs"
rm -rf "mongo/etc"
rm -rf "mongo/examples"
rm -rf "mongo/testdata"
rm -rf "mongo/benchmark"
rm -rf "mongo/vendor"
rm -rf "mongo/internal/test"
rm -rf "mongo/go.mod"
rm -rf "mongo/go.sum"

echo ""
echo "> Update mongoPatchVersion.go"
echo ""

{

  printf "package goext\n"
  printf "\n"
  printf "// %s\n" "$( date +"%Y-%m-%d %H:%M:%S%z" )"
  printf "\n"
  printf "const MongoCloneTag = \"%s\"\n" "$latestTag"
  printf "const MongoCloneCommit = \"%s\"\n" "$latestSHA"

} > mongoPatchVersion.go

echo ""
echo "> Patch mongo"
echo ""

git apply -v _data/mongo.patch

echo ""
echo "Done."