#!/bin/sh
echo "🔍 Checking if the commit includes submodule updates..."

# Get the list of submodules
submodules=$(git config --file .gitmodules --get-regexp path | awk '{print $2}')

# Check if any submodule reference is staged for commit
submodule_updated=0
for submodule in $submodules; do
    if git diff --cached --name-only | grep -q "^$submodule$"; then
        submodule_updated=1
        break
    fi
done

# If no submodule updates are staged, skip the check
if [[ $submodule_updated -eq 0 ]]; then
    echo "✅ No submodule updates detected. Skipping submodule commit check."
else
    echo "🔍 Submodule update detected. Verifying referenced commits exist on remote..."

    for submodule in $submodules; do
        # Check if the submodule itself is staged
        if git diff --cached --name-only | grep -q "^$submodule$"; then
            echo "📦 Checking submodule: $submodule"

            # Get the commit referenced in the superproject
            submodule_commit=$(git rev-parse HEAD:$submodule)

            # Fetch remote references
            git -C "$submodule" fetch origin --quiet

            # Fetch all remote branches
            git -C "$submodule" fetch origin --quiet --all

            # Check if the commit exists in ANY remote branch
            if git -C "$submodule" ls-remote --exit-code origin "$submodule_commit" >/dev/null 2>&1; then
                echo "✅ Submodule $submodule is up-to-date on remote. Proceeding..."
            else
                echo "❌ ERROR: The submodule '$submodule' is referencing commit $submodule_commit, which does NOT exist on any remote branch!"
                echo "🛑 Please push your submodule changes before committing in the superproject."
                echo "👉 Run the following to push:"
                echo "   cd $submodule && git push origin $(git -C $submodule rev-parse --abbrev-ref HEAD)"
                exit 1  # Prevent commit
            fi
        fi
    done

    echo "🎉 All submodule commits are available on remote. Proceeding..."
fi
echo "🔍 Checking for changes in resource/frontend ..."

# Ensure we are in the root directory of the repo
REPO_ROOT=$(git rev-parse --show-toplevel)
cd "$REPO_ROOT" || exit 1

# Check if there are any changes inside resource/frontend
if git diff --cached --quiet -- "resource/frontend"; then
  echo "✅ No changes detected in resource/frontend. Skipping build."
  exit 0
fi

echo "🔄 Changes detected in resource/frontend. Running yarn build ..."

# Move to the frontend directory and run the build command
cd "resource/frontend" || exit 1
yarn build || exit 1

# Add the newly built files to the commit
cd "$REPO_ROOT"
git add resource/dist/
echo "✅ Added built frontend files to commit!"