# 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 REAL TMP ES
    REAL=`command which dpt`
    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" &
    )
    ES=0
    $REAL "$@" > "$TMP/pipe" || ES=$?

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

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

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

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

    return $ES
}
