#!/usr/bin/env bash
set -e

PKG_DIR=$(dirname $0)

CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
AUTO_CONV_SUFFIX="-auto-gen"
REBASED_SUFFIX="-rebased-on-auto-gen"

if ! git diff-index --quiet HEAD --; then
    echo "Current branch '$CURRENT_BRANCH' has uncommitted changes. Please commit or stash them before proceeding."
    exit 1
fi

echo "Automatically converting Nipype tasks to Pydra tasks..."

echo "Create '$CURRENT_BRANCH$REBASED_SUFFIX' and '$CURRENT_BRANCH$AUTO_CONV_SUFFIX' branches if not present and switch to $CURRENT_BRANCH$AUTO_CONV_SUFFIX"
echo "NB: $CURRENT_BRANCH$AUTO_CONV_SUFFIX will contain the conversion specs from '$CURRENT_BRANCH' and the auto-generted tasks,"
echo "wherease '$CURRENT_BRANCH$REBASED_SUFFIX' will be the changes in the current branch rebased on that"
if [ "$CURRENT_BRANCH" == "*$REBASED_SUFFIX"]; then
    BASE_BRANCH=${CURRENT_BRANCH%"$REBASED_SUFFIX"}$AUTO_CONV_SUFFIX
    REBASE_BRANCH=$CURRENT_BRANCH
    git checkout $BASE_BRANCH
else
    REBASE_BRANCH=${CURRENT_BRANCH}$REBASED_SUFFIX
    BASE_BRANCH=${CURRENT_BRANCH}$AUTO_CONV_SUFFIX
    git checkout -b $REBASE_BRANCH
    git checkout -b $BASE_BRANCH
fi


echo "Running auto-generation of MRtrix3 tasks..."
CMD_DIR=$(dirname $(which mrconvert))
python3 $PKG_DIR/generate.py $CMD_DIR $PKG_DIR 3.1.0

echo "Committing converted tasks to ${CURRENT_BRANCH}$AUTO_CONV_SUFFIX..."
git add pydra/tasks/mrtrix3
git commit -m "auto-generated MRtrix3 Pydra tasks" || echo true

echo "Rebasing '$REBASE_BRANCH' to apply changes..."
git checkout $REBASE_BRANCH
git rebase $BASE_BRANCH

echo "Successfully converted Nipype tasks to Pydra tasks and rebased manual edits over the top of them in '$REBASE_BRANCH'
