#!/bin/sh
#
# ident "@(#)utamghref_allkeys_script.sh	1.2 05/05/17 SMI"
#
# Copyright 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
}

genericget() {
    key=$1
    value=$2

    # Output the last value of "chain_amgh"
    get_keyval_pair ${key} ${value} chain_amgh

    # Output the last value of "use_firstserver"
    get_keyval_pair ${key} ${value} use_firstserver

    if [ "X${key}" != "Xusername" ]
    then
            get_keyval_pair ${key} ${value} username
    fi

    # Output the list of all matching hosts
    HOSTS=`get_keyval_pair ${key} ${value} 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 genericget "username" "$username"
	then
	   exit 0
	fi
fi

# if we didn't find any hosts by username, try by token
if [ -n "$token" ]
then
	if genericget "token" "$token"
	then
		exit 0
	fi
fi


#Extensions here
#Other keywords
#terminal_cid, terminal_ip_addr, insert_token, display
if [ -n "$display" ]
then
	if genericget "display" "$display"
	then
		exit 0
	fi
fi

if [ -n "$insert_token" ]
then
	if genericget "insert_token" "$insert_token"
	then
		exit 0
	fi
fi

if [ -n "$terminal_cid" ]
then
	if genericget "terminal_cid" "$terminal_cid"
	then
		exit 0
	fi
fi

if [ -n "$terminal_ip_addr" ]
then
	if genericget "terminal_ip_addr" "$terminal_ip_addr"
	then
		exit 0
	fi
fi

exit 0
