#!/bin/rc

# huntservice SERVICENAME
# searches mounted registries to find SERVICENAME and mounts it

# set variable from argument or prompt user
switch($1){
case ''
	echo This script is usually a fall-back for getsvc.
	echo If you wanted to do a manual registry hunt, enter a service name to search the active registries for.
	SERVICENAME=`{read}
case *
	SERVICENAME=$1
}

rfork ns
echo `{date} huntservice $SERVICENAME >>/tmp/grid/log/log
echo hunting for $SERVICENAME in mounted registries
echo searches backgrounded to avoid long timeouts from dead mounts
echo press DELETE to interrupt

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

# search all mounted registries with parallel greps backgrounded so dead mounts dont hold things up

# g/regnsupdate

for (i in /g/r/*/*/index) {
	grep -i $SERVICENAME $i >>/tmp/grid/work/svcfind &
}

TIMEOUT=0

# loop the info search to wait for the background greps to find a match
while (! ~ $SVCINFO ?*){
	echo attempt number $TIMEOUT
	if (test $TIMEOUT -gt 10) {
		echo search timed out;
		exit
		}
	echo checking for a match
	sleep 9
	SVCINFO=`{tail -1l /tmp/grid/work/svcfind}
	TIMEOUT=`{echo $TIMEOUT+1 |hoc}
}

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 $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
