#! /bin/sh
#
#          make all the components for charissa sunsort
#
. ./config.mk
INSTALL=install
SORT_FILES=
SOURCE=
DESTINATION=
OPENWINHOME=${OPENWINHOME:-/usr/openwin}
usage='Usage: install.sh [-p] [-u] [-d destination] [-s source] -c [sunsort directory names]
		-p tars sunsort  ... must specify destination and source 
		-u untars sunsort ... must specify destination and source 
		-c cleans up sunsort release
		-d destination directory/file
		-s source directory/file'

#
# process user supplied arguments here
#
while getopts pucd:s: option
do
	case "$option"
	in
		p) 	INSTALL=pack;;
		u) 	INSTALL=unpack;;
		c) 	INSTALL=clean;;
		s)      SOURCE=$OPTARG;;
		d)      DESTINATION=$OPTARG;;
		\?)	echo "$usage"
			exit 1;;
		esac
done
shift `expr $OPTIND - 1`
#
#  check whether we want to act only on specified directory
#
while [ $# -gt 0 ]
do 
		SORT_FILES="${SORT_FILES} $1"
		shift
done

#
# set the version of the operating system we expect
#
OS=`uname -r`
OS_VERSION=`(IFS=.; set $OS; echo $1)`
echo "Performing $0 for OS version $OS => using Makefile_$OS_VERSION"

#
# if SORT_FILES is empty assume that we want all files processed
#
if [ -z "$SORT_FILES" ]
then
    SORT_FILES="./sort-spy ./ftnchek_dir ./sunsort_src ./make_tools \
	./sunsort_lib ./sunsort_gui ./display_1d ./display_2d ./buffit_dir \
	./peakfind_dir ./calc_xvgr_dir ./slicing ./ansitp_dir ./sort-subs"
fi

#
# start the making process
#
if [ "$INSTALL" = "install" -o "$INSTALL" = "clean" ]
then
	set ${SORT_FILES}
	while [ $# -gt 0 ]
	do 
		cd $1
		rm -f Makefile
		ln -s Makefile_${OS_VERSION} Makefile
		make $INSTALL VERS=${VERS}
		if [ $? -ne 0 ] 
		then
			echo "error detected in ${1}/Makefile operation"
			exit 3
		fi
		cd ..
		shift
	done
fi
#
#  pack sunsort into tar file
#
if [ "$INSTALL" = "pack" ]
then
	if [ -z "$DESTINATION" ] 
	then
		echo "no destination file specified"
		echo "$usage"
		exit 4
	fi
	if [ -z "$SOURCE" -o ! -d "$SOURCE" ] 
	then 
		echo "no source directory specified or not a valid directory"
		echo "$usage"
		exit 5
	fi
	cd `dirname "$SOURCE"` || exit 6
	SOURCE=./`basename $SOURCE`
	tar cvf "$DESTINATION" "$SOURCE"
	compress "$DESTINATION"
fi
#
# unpack sunsort from tar file
#
if [ "$INSTALL" = "unpack" ]
then
	if [ -z "$DESTINATION" -o ! -d "$DESTINATION" ] 
	then
		echo "no destination directory specified or not a valid directory"
		echo "$usage"
		exit 7
	fi
	if [ -z "$SOURCE" ] 
	then 
		echo "no source file specified"
		echo "$usage"
		exit 8
	fi
	uncompress -c "$SOURCE" | (cd "$DESTINATION"; tar xvf -)
fi


#
echo "installation complete under option '$INSTALL'"
exit 0

