#!/usr/bin/env bash

BASE_BRANCH=rfagen/experiments
TEMP_BRANCH=test-rfagen/experiments
MERGE_TYPE=serial
PR_LIST=""
MERGE_LIST=""

function show_usage {
        echo "Usage: $0 ([--octopus|--serial]) (--base <base_branch>) <PR#> ([PR#],...)"
        echo "where:"
        echo "  --octopus -> a single octopus merge"
        echo "  --serial  ->  merge all PRs serially"
        echo "  --base    -> use <base_branch> branch, default: master"
        echo "  <PR#>     -> a PR # to merge"
        exit 1
}

function merge_failure {
    echo " "
    echo "Failed to merge. Please clean up"
    echo " "
    exit 1
}


while [[ $# > 0 ]]; do
        case $1 in
                -help|--help|-h|--h)
                        show_usage
                        ;;
                --octopus)
                        MERGE_TYPE=octopus
                        ;;
                --serial)
                        MERGE_TYPE=serial
                        ;;
                --base)
                        shift
                        BASE_BRANCH=$1
                        TEMP_BRANCH=test-$BASE_BRANCH
                        ;;
                *)
                        PR_LIST+="$1 "
                        ;;
        esac
        shift
done

if [[ "$PR_LIST" == "" ]]; then
        echo "No PRs specified "
        show_usage
fi

TEMP_BRANCH+="-$MERGE_TYPE"
echo Merging $PR_LIST based on $BASE_BRANCH using working branch $TEMP_BRANCH and merge method $MERGE_TYPE

git checkout $BASE_BRANCH
git branch -D $TEMP_BRANCH
git checkout -b $TEMP_BRANCH

MERGE_RC=0
for PR in $PR_LIST
do
        git fetch origin pull/$PR/head:test_merging/$PR
        if [[ $MERGE_TYPE == serial && $MERGE_RC -eq 0 ]]; then
                git merge --no-ff --no-edit --message "merge $PR" test_merging/$PR
                MERGE_RC=$?
        else
                merge_failure
        fi
        MERGE_LIST+="test_merging/$PR "
done

if [[ $MERGE_TYPE == octopus ]]; then
        git merge --no-ff --no-edit --message "merge $MERGE_LIST" $MERGE_LIST && merge_failure
fi

# clean up
git branch -D $MERGE_LIST
git checkout $BASE_BRANCH
git branch -D $TEMP_BRANCH
