#!/bin/bash

# Path to the TAF CLI executable
TAF_CLI="taf"

output=$($TAF_CLI repo latest-commit-and-branch)
status=$?
DEFAULT_BRANCH=$(echo "$output" | cut -d ',' -f 1)
LAST_VALIDATED_COMMIT=$(echo "$output" | cut -d ',' -f 2)

if [ $status -ne 0 ] || [ -z "$DEFAULT_BRANCH" ] || [ "$DEFAULT_BRANCH" = "None" ]; then
    echo "Could not determine the default branch and the last validated commit. Push aborted."
    echo "Make sure taf is installed and on PATH."
    exit 1
fi

# git passes one line per pushed ref: <local ref> <local sha> <remote ref> <remote sha>
PUSHING_DEFAULT_BRANCH=false
while read -r local_ref local_sha remote_ref remote_sha; do
    if [ "$remote_ref" = "refs/heads/$DEFAULT_BRANCH" ]; then
        PUSHING_DEFAULT_BRANCH=true
    fi
done

if [ "$PUSHING_DEFAULT_BRANCH" = false ]; then
    echo "Skipping validation, not pushing to the default branch"
    exit 0
fi

# Log the commit information before running the validation
if [ -z "$LAST_VALIDATED_COMMIT" ]; then
  echo "No last validated commit found. Starting validation from the beginning"
else
  echo "Starting validation from the last validated commit: $LAST_VALIDATED_COMMIT"
fi


# Run the TAF validation command with --from-latest
$TAF_CLI repo validate --from-latest --no-deps
VALIDATION_STATUS=$?

# Check the validation status
if [ $VALIDATION_STATUS -ne 0 ]; then
  echo "TAF validation failed. Push aborted."
  exit 1
fi

# Allow the push if validation passes
exit 0
