##@cooked comments #-*- coding: utf-8 mode: sh -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8
## Version de ulib utilisable avec n'importe quel bourne shell: le script est
## relancé avec bash si nécessaire
##@cooked nocomments
##@inc[bash
## Relancer le script avec bash si nécessaire
if [ `basename "${BASH:-sh}"` = "sh" ]; then
    bash=`which bash 2>/dev/null`
    for bash in "$bash" /bin/bash /usr/bin/bash /usr/local/bin/bash; do
        if [ -x "$bash" ]; then
            exec "$bash" "$0" "$@"
        fi
    done
    echo "error: this script requires bash"
    exit 1
fi
##@inc]bash
##@inc[ulib
## Charger les librairies de ulib. Nécessite bash.



function eerror() { echo "error: $*" 1>&2; }
function die() { [ -n "$*" ] && eerror "$*"; exit 1; }


ULIBDIR="${FORCED_ULIBDIR:-@@dest@@/ulib}"

if [ "$ULIBDIR" = "@@""dest""@@/ulib" ]; then
    ULIBDIR="${BASH_SOURCE[0]}"
    if [ -n "$ULIBDIR" -a -f "$ULIBDIR" ]; then
        ULIBDIR="$(dirname "$ULIBDIR")"
    else
        ULIBDIR="$(dirname "$0")/ulib"
    fi
fi
ULIBDIR="$(cd "$ULIBDIR"; pwd)"
ULIBDIRS=("$ULIBDIR")

ULIBINIT="$ULIBDIR"

[ -n "$ULIBPROVIDED" ] || ULIBPROVIDED=(ulib)

function uprovided() {
    local ulib_
    for ulib_ in "${ULIBPROVIDED[@]}"; do
        [ "$ulib_" == "$1" ] && return 0
    done
    return 1
}

function uprovide() {
    uprovided "$1" && return 0
    ULIBPROVIDED=("${ULIBPROVIDED[@]}" "$1")
}

function urequire() {
    local ulib_ ulibdir_ found_
    [ -n "$*" ] || set DEFAULTS
    for ulib_ in "$@"; do
        found_=
        for ulibdir_ in "${ULIBDIRS[@]}"; do
            if [ -f "$ulibdir_/$ulib_" ]; then
                found_=1
                if ! uprovided "$ulib_"; then
                    uprovide "$ulib_"
                    source "$ulibdir_/$ulib_" || die
                fi
                break
            elif [ "$ulib_" == "DEFAULTS" ]; then
                found_=1
                for ulib_ in base pretty sysinfos compat; do
                    if ! uprovided "$ulib_"; then
                        uprovide "$ulib_"
                        source "$ulibdir_/$ulib_" || die
                    fi
                done
                break
            fi
        done
        [ -n "$found_" ] || die "Unable to find $ulib_ in ${ULIBDIR[*]}"
    done
}

function ulib_add() {
    [ -d "$1" ] && ULIBDIRS=("${ULIBDIRS[@]}" "$(cd "$1"; pwd)")
}

function ulib_sync() {
    destdir="$(abspath "${1:-.}")"
    [ "$destdir/ulib" != "$ULIBDIR" ] && cpdirnovcs "$ULIBDIR" "$destdir/ulib"
}
##@inc]ulib
uprovide ulibsh