#!/usr/bin/env bash

if [[ $# -gt 1 ]] ; then
    echo "Usage: $0 [<working-directory>]"
    exit 1
fi

DIR="${1:-var/subtree-split/}"
mkdir -p "${DIR}"
pushd "${DIR}" &> /dev/null

echo -e "\e[34mSetup tooling...\e[0m"
if [[ ! -d bin/.git ]] ; then
    echo "Cloning..."
    git clone --quiet git@github.com:msgphp/git-subtree-sync.git bin
    [[ $? -ne 0 ]] && echo "Failed!" && exit 1
fi

git -C bin pull

echo -e "\e[34mSynchronizing source...\e[0m"
if [[ ! -d main/.git ]] ; then
    rm -rf .gitsubtree main subtrees
    mkdir main subtrees
    echo "Cloning..."
    git clone --quiet git@github.com:msgphp/msgphp.git main
    [[ $? -ne 0 ]] && echo "Failed!" && exit 1
fi

git -C main fetch --tags
git -C main pull

if [[ ! -f .gitsubtree ]] ; then
    PACKAGES=""
    for PACKAGE in $(find main/src/*/composer.json -type f) ; do
        PACKAGE_NAME=$(grep -E "^\s*\"name\"\s*:\s*\"msgphp\/([^\"]+)\"\s*,\s*$" "${PACKAGE}")
        if [[ ! -z $PACKAGE_NAME ]] ; then
            PACKAGE_NAME=$(echo "${PACKAGE_NAME}" | sed -e "s/^\s*\"name\":\s*\"msgphp\///" -e "s/\"\s*,\s*$//")
            PACKAGE_PATH="src/$(basename $(dirname "${PACKAGE}"))/"
            echo -e "\e[34mFound package \"msgphp/${PACKAGE_NAME}\" at \"${PACKAGE_PATH}\"\e[0m"
            PACKAGES="$PACKAGES    [\"${PACKAGE_NAME}\"]=\"${PACKAGE_PATH}\""$'\n'
        fi
    done

    cat >.gitsubtree <<EOL
REMOTE_BASE_URL=git@github.com:msgphp
MONOLITH_REPO_ROOT=\$(realpath main)
SUBTREE_REPO_ROOT=\$(realpath subtrees)
PREFIX_DIRS=(
$PACKAGES)
EOL
fi

bin/git-subtree-sync.sh

popd &> /dev/null
