#!/bin/bash

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

output=$($TAF_CLI repo latest-commit-and-branch)

if [ $? -ne 0 ]; then
    echo "Failed to retrieve the last validated commit."
    DEFAULT_BRANCH=""
    LAST_VALIDATED_COMMIT=""
else
    # If the command succeeded, parse the output
    DEFAULT_BRANCH=$(echo "$output" | cut -d ',' -f 1)
    LAST_VALIDATED_COMMIT=$(echo "$output" | cut -d ',' -f 2)
fi


CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)

if [ "$CURRENT_BRANCH" != "$DEFAULT_BRANCH" ]; 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
