#!/bin/bash

PROG_NAME_="`basename $0`"
HGROOT_=""
MQROOT_=""
MQPATCH_=""  # applied patch before if any


function stringInString
{
    local to_test_="$1"   # matching pattern
    local source_="$2"    # string to search in

    case "$source_" in *$to_test_*) return 0;; esac
    return 1
}

function printUsage
{
    cat <<EOT
Usage: $PROG_NAME_ <action> [ <options> ]

$PROG_NAME_ is a wrapper over hg with mq support for often used command sequenzes.

ACTIONS:
All actions pop patches from stack, execute the command on both repositories
and recreate the stack layout afterwards, if not stated otherwise.
All options given after the action are automatically forwarded to hg.

   push         hg push
   pull         hg pull
   up|update    hg update
   in           hg in (this command does not touch the stack)
   out          hg out
EOT
    exit 1
}

function callHG
{
    hg $@
    hg -R "$MQROOT_" $@
}

function prepareMQ
{
    local ret_="1"
    hg qtop &>/dev/null || return 0
    local tmp_=`hg qtop`
    if [[ $tmp_ != "" ]]; then
        MQPATCH_="$tmp_"
        hg qpop -a
    fi
}

function recreateMQ
{
    if [[ $MQPATCH_ != "" ]]; then
        hg qpush "$MQPATCH_"
    fi
}

function defaultAction
{
    local CMDS_="up update push pull out"
    local cmd_="$1"; shift
    if stringInString "$cmd_" "$CMDS_"; then
        prepareMQ
        callHG "$cmd_" "$@"
        recreateMQ
    else
        echo "W: command not implemented yet"
        printUsage
    fi
}

function actionIn
{
    local cmd_="$1"; shift
    callHG in "$@"
}

set -e
if [[ $DEBUG != '' ]]; then
    set -x
fi

HGROOT_="`hg root`"
MQROOT_="${HGROOT_}/.hg/patches"

case $1 in
    in) actionIn "$@"; exit 0;;
    "") printUsage ;;
    *) defaultAction "$@"; exit 0;;
esac

# vim: filetype=sh
