#!/bin/bash

while getopts "qv:" OPT; do
    case "$OPT" in
	q)
	QUIET=1
	;;
	v)
	VERSION="$OPTARG"
	;;
    esac
done

if [ -z "$VERSION" ]; then
    if [ -d "/sys/hypervisor" ]; then
        if [ "$(cat /sys/hypervisor/type)" = xen ]; then
            dir=/sys/hypervisor/version/
            VERSION="$(cat $dir/major).$(cat $dir/minor)$(cat $dir/extra)"
        else
            [ "$QUIET" ] || echo "WARING!  Can't read type from sysfs!" >&2
        fi
    else
        [ "$QUIET" ] || echo "WARING!  Can't find hypervisor information in sysfs!" >&2
    fi
fi

if [ -z "$VERSION" ]; then
    VERSION="default"
fi

if [ -d "/usr/lib/xen-$VERSION" ]; then
    echo "$VERSION"
    exit 0
fi

if [ -d "/usr/lib/xen-default" ]; then
    [ "$QUIET" ] || echo "WARING!  Can't find version $VERSION of xen utils, fallback to default version!" >&2
    echo "default"
    exit 0
fi

[ "$QUIET" ] || echo "ERROR!  Can't find default version of xen utils, bailing out!" >&2
exit 1
