#!/bin/rc

# getsvc SERVICENAME
# finds and mounts the named service based on reg info cached in /tmp/grid
# if the service is not found there, calls huntservice SERVICENAME to query mounted registries

# set variable from arguments or prompt user 
switch($1){
case ''
	echo Enter a service name
	SERVICENAME=`{read}
	echo use getsvc SERVICENAME to skip this prompt
case *
	SERVICENAME=$1
}

rfork ns
# clear old work files if present
if (test -e /tmp/grid/work/svcfind) rm /tmp/grid/work/svcfind
if (test -e /tmp/grid/work/svctarget) rm /tmp/grid/work/svctarget

echo `{date} getsvc $SERVICENAME >>/tmp/grid/log/log

# find all lines with info matching the requested service 
# then pick the most recently added 

grep -i $SERVICENAME /tmp/grid/info/regbucket >/tmp/grid/work/svcfind
SVCINFO=`{tail -1l /tmp/grid/work/svcfind}

# if we didnt find any SVCINFO from grepping the regbucket
# call huntservice to query currently mounted registries

if (! ~ $SVCINFO ?*) {
	echo not found in service cache, using huntservice $SERVICENAME; g/huntservice $SERVICENAME; exit
}

echo found service info $SVCINFO
echo $SVCINFO >/tmp/grid/work/svctarget
DIALSTRING=`{awk '{print $1}' /tmp/grid/work/svctarget}
echo attempting mount at /g/$SERVICENAME/s using $DIALSTRING as dialstring
if (recover $DIALSTRING $SERVICENAME) {
	g/local mntgen /g/$SERVICENAME
	sleep 1
	g/local mount /srv/$SERVICENAME /g/$SERVICENAME/s
	g/svcadd $SERVICENAME $DIALSTRING 
	exit
}
echo bad dialstring guess, trying to find a better one
PORT=`{echo $DIALSTRING |awk -F! '{print $3}'}

# look at how many strings there are in the svctarget info and count through them
# look for a string that seems like it could be used in a dialstring and try dialing it

for (i in `{seq 2  `{cat /tmp/grid/work/svctarget |wc -w}}){
	IPADDR=`{awk '{print $'$i'}' /tmp/grid/work/svctarget |sed s/at//}
	if (! ~ $IPADDR ?*) IPADDR=null
	TESTADDR=`{echo $IPADDR |awk -F. '{print $2}'}
	DIALSTRING=tcp!$IPADDR!$PORT
	if (~ $TESTADDR ?*) {
		echo attempting mount at /g/$SERVICENAME/s using $DIALSTRING as dialstring
		if (recover $DIALSTRING $SERVICENAME) {
			g/local mntgen /g/$SERVICENAME
			sleep 1
			g/local mount /srv/$SERVICENAME /g/$SERVICENAME/s
			g/svcadd $SERVICENAME $DIALSTRING; exit
		}
	}
	echo dialstring still failed, looking for more possibilities
}

echo failed to deduce correct dialsting. try manually mounting based on
echo $SVCINFO


# this script part of the /g/toolkit licensed under the MIT license but be cool
# keep the code open, share your scripts and config files
