#!/bin/sh
# Push content subrepo before pushing main repo

remote="$1"

. "$(pwd)/.env"
if [ "$SKIP_TESTS" = "true" ]; then
  exit 0
fi

set -eu
set -x

hook_input=$(cat)
echo "$hook_input"

read_branches() {
  matched=false
  seen_refs=false

  echo "$hook_input" | while IFS=' ' read -r _ _ remote_ref _; do
    seen_refs=true
    case "$remote_ref" in
      refs/heads/testing|refs/heads/staging|refs/heads/main|refs/heads/production)
        echo "Matched deployable branch: ${remote_ref#refs/heads/}"
        exit 0
        ;;
      *)
        echo "Non-deployable branch: ${remote_ref#refs/heads/}"
        ;;
    esac
  done

  if ! $seen_refs; then
    echo "No refs were pushed. Nothing to process."
    return 2
  fi

  echo "No deployable branches matched."
  return 1
}

check_submodule_remotes() {
  git submodule foreach --quiet "
    if ! git remote get-url \"$remote\" > /dev/null 2>&1; then
      echo \"Error: submodule '\$name' missing remote '$remote'.\"
      exit 1
    fi
  "
}

read_branches_result=2
read_branches || read_branches_result=$?

case "$read_branches_result" in
  0)
    COMMIT_HASH=$(git rev-parse HEAD)
    if ! ./scripts/pre-push-tests.sh "$COMMIT_HASH"; then
      echo "Tests failed. Aborting push."
      exit 1
    fi
    ;;
  1)
    echo "Skipping tests: no deployable branches pushed."
    ;;
  2)
    echo "No refs detected. Possibly a dry push or no changes."
    ;;
esac

cd content
git push "$remote" main --force
cd ..
set +x
