#!/usr/bin/env bash
set -euo pipefail

# like `check-if-branch-current`, but for all the submodules, recursive.

# <git ✨>
# the lowercase variables come from git
# lines explained in order:
# - go to superproject (for this level of recursion)
# - get current commit from remote master
# - get current commit of submodule in current commit from remote master
#     - abort if not found (bc it's a newly added submodule)
# - go to the submodule
# - check that the current submodule commit is still contained in tree
git submodule foreach --recursive '\
  cd "${toplevel}" \
  && SUPER_HASH="$(git rev-parse origin/master)" \
  && SUB_HASH=$(git rev-parse ${SUPER_HASH}:${path}) \
    || { echo "new submodule - dont check!" && exit 0 ;} \
  && cd "${path}" \
  && git rev-list --children HEAD | grep -q "^${SUB_HASH}" \
    || { echo "FAIL! submodule ${path}" lost commit ${SUB_HASH}; exit 1 ;}'
# </git ✨>

echo "OK"
