#!/bin/rc

# regrepair
# checks list of mia registries, attempts to remount, discards if impossible


rfork ns
echo `{date} regrepair >>/tmp/grid/log/log
RESCUE1=0
RESCUE2=0

# for each missing registry, unmount it, remove the srv, and try reconnect
# test the reconnection, and add the information to the service index
# if the rescue fails, move the registry to the dedreg directory

for (i in /tmp/grid/miareg/*){
	if (! ~ $i '/tmp/grid/miareg/*'){
		REGNAME=`{echo $i |awk -F/ '{print $5}'}
		DIALSTRING=`{cat /tmp/grid/miareg/$REGNAME}
		g/local unmount /g/r/$REGNAME/r
		sleep 5
		rm /srv/$REGNAME
		if (recover $DIALSTRING $REGNAME) RESCUE1=success
		if (~ $RESCUE1 success){
			sleep 2
			g/local mount /srv/$REGNAME /g/r/$REGNAME/r			
			sleep 5
			touch /tmp/grid/work/testreg$REGNAME
			rc -c 'ls /g/r/$REGNAME/r >>/tmp/grid/work/testreg$REGNAME' &
			sleep 4
			if (test -e /proc/$apid) echo kill>/proc/$apid/note
			sleep 2
			if (test -e /proc/$apid) echo kill>/proc/$apid/ctl
			RESCUE2=`{cat /tmp/grid/work/testreg$REGNAME}
			if (~ $RESCUE2 ??*){
				echo `{date} RESCUE of $REGNAME >>/tmp/grid/log/log
				mv /tmp/grid/miareg/$REGNAME /tmp/grid/registries/$REGNAME
				cat /g/r/$REGNAME/r/index >/tmp/grid/info/reg$REGNAME
				cat /tmp/grid/info/reg$REGNAME >>/tmp/grid/info/regbucket
				echo registry $REGNAME rescued remember to reannounce
				grep $REGNAME /tmp/grid/log/log |grep tellreg
			}
		}	
		if (! ~ $RESCUE2 ??*){
			echo `{date} DEAD REG $REGNAME removed >>/tmp/grid/log/log
			echo rescue of registry $REGNAME failed marking as dead
			if (test -e /srv/$REGNAME) rm /srv/$REGNAME
			mv /tmp/grid/miareg/$REGNAME /tmp/grid/dedreg/$REGNAME
			mv /tmp/grid/registries/$DIALSTRING /tmp/grid/dedreg/$DIALSTRING
			mv /tmp/grid/info/reg$REGNAME /tmp/grid/info/dedrg$REGNAME
		}
	}
}

if (test -e /tmp/grid/info/miareg/*) rm /tmp/grid/info/miareg/*
if (test -e /tmp/grid/work/testreg*) rm /tmp/grid/work/testreg*

echo completed attempted fixups for broken registry mounts
