#!/bin/sh -e

configfile=/etc/default/xen

dir=$(. /usr/lib/xen-common/bin/xen-dir); ret=$?; [ $ret -eq 0 ] || exit $ret

check() {
    local PATH
    if [ "$1" = xm ] || [ "$1" = xl ]; then
        PATH="$dir/bin"
    else
        PATH="$dir/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
    fi
    command -v "$1" || :
}

if [ -e $configfile ]; then
    . $configfile || true
fi

if [ "$TOOLSTACK" ]; then
    cmd=$(check "$TOOLSTACK")
    if [ "$cmd" ]; then
        echo "$cmd"
    else
        echo "WARING:  Can't find toolstack $TOOLSTACK, fallback to default!" >&2
        TOOLSTACK=
    fi
fi

if [ -z "$TOOLSTACK" ]; then
    cmd_xm=$(check xm)
    cmd_xl=$(check xl)
    if [ "$cmd_xm" ]; then
        echo "$cmd_xm"
    elif [ "$cmd_xl" ]; then
        echo "$cmd_xl"
    else
        echo "ERROR:  Toolstack not specifed and nothing detected, bailing out!" >&2
        exit 127
    fi
fi
