#!/usr/bin/env bash
EXEC="/usr/sbin/hsflowd"
EXTRA_ARGS=""

#
# A function to test the form of a UUID string
#
is_uuid() {
    local UUID_REGEX;
    UUID_REGEX='^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$'
    # newer bash supports the =~ operator but for backwards compatibility we use grep
    echo $1 | egrep $UUID_REGEX >/dev/null;
}

#
# A function to try and find a UUID for this host
#
inm_uuid() {
    local MYUUID;

    if [ -x /usr/sbin/dmidecode ]; then
        # from the BIOS
        MYUUID=`/usr/sbin/dmidecode 2>/dev/null | awk -- '/UUID/{print $2}'`
        if is_uuid $MYUUID; then
            echo $MYUUID
            return 0;
        fi;
    fi

    if [ -d /dev/disk/by-uuid ]; then
        # first local disk
        MYUUID=`ls /dev/disk/by-uuid | head -n 1`;
        if is_uuid $MYUUID; then
            echo $MYUUID
            return 0;
        fi;
    fi

    if [ -x /sbin/blkid ]; then
        # first local disk (via 'blkid')
        MYUUID=`blkid 2>/dev/null | awk -vRS=" " -vFS="=" -- '/UUID/{print $2}' | tr -d '"' | head -1`;
        if is_uuid $MYUUID; then
            echo $MYUUID
            return 0;
        fi;
    fi

    # vol_id, tune2fs are additional options. Or a UUID can be set in the configuration file

    echo "not found";
    return 1
}


if UUID=`inm_uuid`; then
    EXTRA_ARGS="-u ${UUID}";
fi

if [ -f /var/run/cl-mgmtvrf ]; then
    EXEC="LD_PRELOAD=sockmark.so ${EXEC}"
fi

eval $EXEC
