#!/bin/sh
#
# ident "@(#)utamghref_script.sh	1.6 05/05/17 SMI"
#
# Copyright 2004-2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#


DBFILE=/opt/SUNWutref/amgh/back_end_db

get_keyval_pair() {
    key=$1
    value=$2
    return_key=$3

    opt_all=$4 #Optional -- set to ALL if you need all matching lines.
                #Default is to output only the last matching line

    if [ "X${opt_all}" = "XALL" ]
    then
        sed -n "s/^${key}=${value}[ 	].*\(${return_key}=[^	 ]*\).*/\1/p" $DBFILE
    else
        sed -n "s/^${key}=${value}[ 	].*\(${return_key}=[^	 ]*\).*/\1/p" $DBFILE | tail -1
    fi
}

getbytoken() {
    # Look for lines that begin with the token keyword and match the supplied token
    # Output the last username seen on any such lines
    get_keyval_pair token ${token} username
 
    # Look for lines that begin with the token keyword and match the supplied token
    # Construct a list of all hosts seen on any such lines
    get_keyval_pair token ${token} host ALL
}

getbyusername() {
    # Look for lines that begin with the username keyword and match
    # the supplied username.
    # Output the list of all hosts seen on any such lines
    HOSTS=`get_keyval_pair username ${username} host ALL`

    # If any hosts were matched, output them and return success
    if [ -n "$HOSTS" ]
    then
	echo "$HOSTS"
	return 0
    fi
    return 1
}

# parse the args into shell vars
while read A
do
    eval "$A"
done

# exit if the mapping file is missing.
if [ ! -f "$DBFILE" ]
then
    echo "$0: Missing mapping file" 1>&2
    exit 3
fi

# if a username is provided, use it for the lookup
if [ -n "$username" ]
then
	# if we find any hosts by username, we're done
	if getbyusername
	then
	   exit 0
	fi
fi

# if we didn't find any hosts by username, try by token
getbytoken
exit 0
