#!/bin/bash
set -euo pipefail

# Store the initial git status
initial_status=$(git status --porcelain)

# Run the lint command
yarn run lint --fix

# Store the status after running lint
post_lint_status=$(git status --porcelain)

# Compare the initial and post-lint statuses
if [ "$initial_status" != "$post_lint_status" ]; then
  echo "===================================="
  echo "Linters gonna lint!"
  echo "Linting made changes. Please commit these changes before pushing or push with --no-verify flag to omit this check."
  echo "===================================="
  exit 1
fi

# Run type-check on all workspaces
if ! yarn run type-check; then
  echo "===================================="
  echo "Type check failed. Please fix the type errors before pushing or push with --no-verify flag to omit this check."
  echo "===================================="
  exit 1
fi

# Check if the user wants to run tests on push
if [ "${RUN_TESTS_ON_PUSH:-}" == "true" ]; then
  echo "Running tests..."
  if ! yarn test; then
    echo "===================================="
    echo "Tests failed. Guess they need more 'exercise'!"
    echo "Please fix the issues before pushing or push with --no-verify flag to omit this check."
    echo "===================================="
    exit 1
  fi
fi

# All goooood in safe's land!
exit 0
