#!/bin/sh

#  scsiremap v. 0.90

#  Copyright (C) 2001, Compaq Computer Corporation 
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2, or (at your option)
#  any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

try()
{
	$@
	status="$?"
	if [ "$status" != "0" ]
	then
		echo "scsiremap: Command $@ failed, exit code $?" 1>&2
		exit 1
	fi
}
	
CURRENT=/etc/scsimap.current
CANONICAL=/etc/scsimap.canonical
if [ ! -f $CANONICAL ]
then
	echo "scsiremap: $CANONICAL does not exist." 1>&2
	exit 1
fi

if [ "$*" = "" ]
then
	try scsimap /dev/sd* /dev/cciss/c*d*p* > $CURRENT
else
	try scsimap $* > $CURRENT
fi

done=no
while [ "$done" = "no" ]
do
	read x
	if [ "$?" != "0" ]
	then
		exit 0	
	fi

	pattern=`echo "$x" | sed -e 's/[^:]*[:]/:/'`
	firstmatch=`grep -F "$pattern" "$CURRENT" | head -1`
	lastmatch=`grep -F "$pattern" "$CURRENT" | tail -1`
	devnode=`echo $x | sed -e 's/[:].*//'`
	rm -f $devnode
	if [ "$firstmatch" != "$lastmatch" ]
	then
		echo "scsiremap: duplicate entries:" 1>&2
		echo "scsiremap: $firstmatch" 1>&2
		echo "scsiremap: $lastmatch" 1>&2
		echo "scsiremap: Ignoring device $devnode" 1>&2
	else
		if [ "$lastmatch" = "" ]
		then
			echo "scsiremap: Device $devnode seems to be missing.  Ignoring." 1>&2
		else 
			# echo "scsiremap: Found match for $devnode : $lastmatch"
			realdevnode=`echo "$lastmatch" | sed -e 's/[:].*//'`
			ln -s "$realdevnode" "$devnode"
		fi
	fi
	
done < $CANONICAL

