# shell functions library
# to be sourced, not executed
# Copyright (c) 2013 Damyan Ivanov <dmn@debian.org>
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of either:
#
#    a) the GNU General Public License as published by the Free Software
#       Foundation; either version 1, or (at your option) any later
#       version, or
#
#    b) the "Artistic License" which comes with Perl.
#
# the purpose of this is to parse the output of 'dpt checkout' and 'dpt cd'
# commands and change the CWD accordingly

dpt() {
    local TMP ES
    ES=0

    case "$1" in
        cd|co|checkout)
            # continue below
            ;;
        *)
            command dpt "$@" || ES=$?
            return $ES
            ;;
    esac

    TMP=`mktemp -d --suffix=.dpt`
    if [ -n "${BASH:-}" ]; then
        trap "command rm -rf '$TMP'" RETURN
    else
        trap "command rm -rf '$TMP'" EXIT
    fi
    mkfifo "$TMP/pipe"
    (
    set +m
    tee "$TMP/out" < "$TMP/pipe" &
    )
    command dpt "$@" > "$TMP/pipe" || ES=$?

    [ -e "$TMP/out" ] || return $ES

    if [ `grep -E -c "^Updating existing checkout in .+" "$TMP/out"` = 1 ]; then
        DIR=`grep -E '^Updating existing' "$TMP/out" | sed -e 's/Updating existing checkout in //'`
        cd "$DIR"
        return $ES
    fi

    if [ `grep -E -c "^.+ ready in .+" "$TMP/out"` = 1 ]; then
        DIR=`grep -E ' ready in ' "$TMP/out" | sed -e 's/.\+ ready in //'`
        cd "$DIR"
        return $ES
    fi

    if [ `grep -E -c "^Package .+ is in .+" "$TMP/out"` = 1 ]; then
        DIR=`grep -E '^Package .+ is in ' "$TMP/out" | sed -e 's/^Package .\+ is in //'`
        cd "$DIR"
        return $ES
    fi

    return $ES
}
