#!/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.

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

