#!/bin/sh
#
#*****************************************************************************
#                                                                            *
#            Copyright (C) 1996, Alias|Wavefront                             *
#                                                                            *
#    These coded instructions,  statements and  computer programs contain    *
#    unpublished information proprietary to Alias Research, Inc.  and are    *
#    protected by the Canadian and US Federal copyright law. They may not    *
#    be disclosed to third parties  or copied  or duplicated, in whole or    *
#    in part,  without the prior written consent of Alias Research,  Inc.    *
#                                                                            *
# Unpublished-rights reserved under the Copyright Laws of the United States. *
#                                                                            *
#****************************************************************************/
#
#
# Plug-in manager
#	This script is used for managing plug-ins.  It includes functionality for
#		- installing plug-ins
#		- removing plug-ins
#		- making plug-ins active
#		- building plug-in pim (plug-in manager) files
#		- appending to plug-in pim files 
#
#	This script requires that $HOME, $ALIAS_WORKENV and $ALIAS_LOCATION are correctly
# 	set in the user'e environment.
#
#	This script is broken into different sections such as reporting, utilities,
# 	tar file code etc.
#	Functions that return values should return 0 if the function succeeded or
# 	non-zero if they failed.
#	For the logging, in the command line mode, errors will be echoed back.
#	In gui mode, we write errors to the screen with the aliasWarning
#	program.  If that fails we write to the Alias error log or echo to
# 	console as a last resort. 

#
# Variables
#

set_variables() {
	# Debug flag, make non-zero to turn on debugging
	debug=0
	if [ ! -z "$ALIAS_PIM_DEBUG" ]
	then
		debug=1
	fi

	#
	# Globals we use in this script.
	local_plugin_path="$HOME/.Alias/plugins"
	global_plugin_path="$ALIAS_LOCATION/ODS/OpenAlias/plugins"
	plugin_path="$local_plugin_path"
	character_read=""
	current_temp_files=""
	temp_dir="."
	gui_mode=0
	html_list=""
	html_index_file="index.html"

	#
	# Header = application, version of application,archive type, version of pim 
	# This info will be used to control versions of the archives. 
	pim_header_length=100
	tar_start_pos=102 # 101 is the new line and 102 is the start 
	pim_header="[Alias Studio][Version 7.5][PIM][Version 1.0]"
	length=`echo $pim_header | wc -c`
	while [ "$length" -le "$pim_header_length" ]
	do
		pim_header="$pim_header."
		length=`expr $length + 1`
	done
 
	#
	# Used in gui dialog prompts
	prompt_title="Plug-in Manager"

	# find a temporary directory
	if [ -z "$TMPDIR" ]
	then
		temp_dir="/usr/tmp"
		if [ ! -d "$temp_dir" ]
		then
			temp_dir="/tmp"
			if [ ! -d "$temp_dir" ]
			then
				temp_dir="."
			fi 
		fi
	else
		temp_dir="$TMPDIR"
	fi

	# path
	PATH="/usr/bin:/usr/bsd"

	#
	# Set which variables are read-only
	readonly local_plugin_path global_plugin_path pim_header	\
		 pim_header_length prompt_title temp_dir html_index_file\
		tar_start_pos
}

#
# debugging, error and info reporting
#

debugMsg() {
    if [ "$debug" -ne 0 ]
    then
        echo Debug: $*
    fi
}

errorMsg() {
	if [ "$gui_mode" -eq 1 ]
	then
		guiDialog "Error: $*" -bOK
	else
		echo Error: $*
	fi
}

infoMsg() {
	echo Info: $*
}

blankLine() {
	echo
}

logErrorMsg() {
	if [ ! -z "$ALIAS_WORKENV" ]
	then
		echo Error: $* >> $ALIAS_WORKENV/errlog
	fi
	echo Error: $*
}

guiDialog() {
	if [ $# -lt 2 ]
	then
		errorMsg "guiDialog needs at least 2 parameters"
		return
	fi

	dialog_msg="$1"
	shift

	gui_result=""

	msg_length=`echo "$dialog_msg" | wc -c `
	if [ "$msg_length" -gt 41 ] 
	then
		saved_msg="$dialog_msg"
		dialog_msg=""
		count=1
		line_length=1
		addUntilSpace=0
		while [ "$count" -le "$msg_length" ]
		do
			Char=`expr substr "$saved_msg" "$count" 1`
			split=`expr $line_length % 40`
			if [ "$addUntilSpace" -eq 1 ]
			then
				if [ "$Char" = " " ]
				then
					dialog_msg="$dialog_msg\n"
					addUntilSpace=0
					line_length=0
				else
					dialog_msg="$dialog_msg$Char"
				fi
			else
				if [ "$split" -eq 0 ]
				then
					if [ "$Char" != " " ]
					then
						dialog_msg="$dialog_msg$Char"
						addUntilSpace=1
					else
						dialog_msg="$dialog_msg\n"
						line_length=0
					fi
				else
					dialog_msg="$dialog_msg$Char"
				fi
			fi
			count=`expr $count + 1`
			line_length=`expr $line_length + 1`
		done
	fi

	gui_result=`echo "$dialog_msg" | \
 		sed -e 's/^ //g'	| \
		$ALIAS_LOCATION/bin/aliasWarning -t"$prompt_title" $* -f - `
}

#
# Ask routines
#	Return values will be positive for Yes, Continue and Local.  A zero
# 	will indicate No, Abort or Global.
#
askYesNo() {
	if [ $# -ne 1 ]
	then
		errorMsg "askYesNo: needs 1 parameter"
		return
	fi
	askQuestion "$1" "Yes" "No" "y" "n"
	return "$?"
}

askContinueAbort() {
	if [ $# -ne 1 ]
	then
		errorMsg "askContinueAbort: needs 1 parameter"
		return
	fi
	askQuestion "$1" "Continue" "Abort" "c" "a"
	return "$?"
}

askLocalGlobal() {
	if [ $# -ne 1 ]
	then
		errorMsg "askLocalGlobal: needs 1 parameter"
		return
	fi
	askQuestion "$1" "Local" "Global" "l" "g"
	return "$?"
}

askQuestion() {
	# parameters are : 	message gui_button1 gui_button2 
	#	command_line_response1 command_line_response2
	if [ $# -ne 5 ]
	then
		errorMsg "askQuestion: needs 5 parameter"
		return 0
	fi

	if [ "$gui_mode" -eq 1 ] 
	then 
		guiDialog "$1" "-b$2" "-b$3"	
		if [ "$gui_result" = "$2" ]
		then
			return 1
		else 
			return 0
		fi
	else
		echo "$1 ($4/$5)"
		readUntilChars "$4" "$5"
		if [ "$character_read" = "$4" ]
		then
			return 1
		else 	
			return 0
		fi
	fi
	return 0	
}

promptOK() {
	if [ $# -ne 1 ]
	then
		errorMsg "promptOK: needs 1 parameter"
		return
	fi

	if [ "$gui_mode" -eq 1 ]
	then
		guiDialog "$1" -bOK
	else
		# no equivalent thing on the command line
		echo "$1"
	fi
}

#
# Trap utilities: deletes temporary files when a users cancels
# the current operation.
#

trap_remove_temp_files() {
	debugMsg "remove_temp_files : $current_temp_files"

	for temp_file in $current_temp_files
	do
		if [ -f "$temp_file" ]   
		then 
			infoMsg " Removing temporary file : $temp_file"
			restrictedRm "$temp_file"
		fi
	done
}

remove_temp_file_name() {
	debugMsg "remove_temp_file_name : $*"
	if [ $# -ne 1 ]
	then
		errorMsg "remove temp file should be passed exactly 1 file"
		return
	fi
	file_to_remove="$1"

	cache_temp_file_names=""
	for temp_file in $current_temp_files
	do
		if [ "$temp_file" != "$file_to_remove" ]
		then
			cache_temp_file_names="$cache_temp_file_names $temp_file"
		fi		
	done
	current_temp_files="$cache_temp_file_names"
}

save_temp_file_name() {
	debugMsg "save_temp_file_name : $*"
	if [ $# -ne 1 ]
	then
		errorMsg "set current temp file should be passed exactly 1 file"
		return
	fi
	current_temp_files="$current_temp_files $1"	
}

set_trap() {
	trap exit    1 2 3 4 5 6 7 8  15 16
	trap trap_remove_temp_files 0
}

#
# hmtl support 
#
build_html_index() {

	if [ $# -ne 2 ]
	then
		errorMsg "html index builder needs 2 parameters"
		return
	fi

	archive="$1"
	htmlfile="$2"

	fName="$plugin_path/$html_index_file"
	if [ ! -f "$fName" ]
	then
		echo '<title>Installed Plug-ins</title>' > $fName
		echo '<h1>Plug-ins</h1>' >> $fName
		echo '<br>' >> $fName
		echo 'The Alias|Wavefront Web page provides information and examples of the OpenAlias plug-in architecture.' >> $fName
		echo 'Click on the following reference to browse this web page.' >> $fName
		echo '<br>' >> $fName
		echo '<a href=http://brahma.alias.com:8001/Support/API/htmls/Alias_Download_Directory.html> Alias|Wavefront Plug-in Web Page</a>' >> $fName
		echo '<br>' >> $fName
		echo '<hr>' >> $fName
		echo '<h1>Installed Web Pages</h1>' >> $fName
		echo 'The following links to plug-in web pages have been installed on your system:' >> $fName
		echo '<br>' >> $fName
	fi
	
	# only add it if its not already there
	found=`grep $archive $fName | wc -l`
	if [ "$found" -eq 0 ]
	then
		echo '<br>' >> $fName
		echo "Click <a href=$htmlfile>Archive $archive</a>" >> $fName
	fi
}

# 
# specific routine for comparing versions
#
valid_version() {

	if [ $# -ne 1 ]
	then
		errorMsg "version comparision routine needs one parameter"
		return
	fi

	app_name=`echo $pim_header | cut -f1 -d] `
	app_vers=`echo $pim_header | cut -f2 -d] `
	pim_type=`echo $pim_header | cut -f3 -d] `
	pim_vers=`echo $pim_header | cut -f4 -d] `

	debugMsg " valid_version : $app_name : $app_vers : $pim_type : $pim_vers"

	file_header=`head -1 $1`
	if [ -z "$file_header" ]
	then
		return 1
	fi
	file_app_name=`echo $file_header | cut -f1 -d] `
	file_app_vers=`echo $file_header | cut -f2 -d] `
	file_pim_type=`echo $file_header | cut -f3 -d] `
	file_pim_vers=`echo $file_header | cut -f4 -d] `
	
	debugMsg " file_version  : $file_app_name : $file_app_vers : $file_pim_type : $file_pim_vers"

	# app names must match
	if [ "$app_name" != "$file_app_name" ]
	then 
		return 1
	fi
	# archive types must match
	if [ "$pim_type" != "$file_pim_type" ]
	then
		return 1
	fi

	if [ "$pim_vers" != "$file_pim_vers" ]
	then
			# This section needs to have more cases filled in
			# as we have different versions.  Right now we
			# fail if the versions are different.
			return 1
	fi	
	return 0
}

# 
# Disk space routines
#
GetDu() {
    du -sk $1 | sed -e 's/[     ].*//' | cut -f1
}

GetDf() {
    df -k ${1:-.} | sed -n -e '2s/^[^   ][^     ]*[     ]*[^    ][^     ]*[     ]*[^    ][^   ]*[     ]*[^    ][^     ]*[     ]*\([^  ][^     ]*\)[   ]*.*/\1/p'
}

check_file_space() {

	if [ $# -ne 2 ]
	then
		errorMsg "check_file_space needs two parameters"
		return 1
	fi

	file_space=`GetDu $1`
	avail_space=`GetDf $2`

	debugMsg "file $file_space : avail $avail_space"

	if [ "$file_space" -gt "$avail_space" ]
	then
		errorMsg "not enough disk space for '$1' in '$2'"
		return 1
	fi
	return 0
}

check_temp_space() {

	if [ $# -ne 1 ]
	then
		errorMsg "check_temp_space needs one parameter"
		return 1 
	fi

	file_space=10 # estimate 10K
	avail_space=`GetDf $1`

	debugMsg "file $file_space : avail $avail_space"

	if [ "$file_space" -gt "$avail_space" ]
	then
		errorMsg "not enough temporary disk space in '$1'"
		return 1
	fi
	return 0
}

#
# Utility routines
#

relpath() {
	ret=0   
	for name in $*
	do
		case "$name" in
		/*)		ret=1;;
		../*)	ret=1;;
		esac
	done
	return "$ret"
}

abspath() {
	ret=0   
	for name in $*
	do
		case "$name" in
		/*)		;;
		*)	ret=1;;
		esac
	done
	return "$ret"
}

validfiles() {
	ret=0
	for name in $*
	do
		case "$name" in
		  lib/*.plugin)	debugMsg "got file $name";;
		./lib/*.plugin)	debugMsg "got file $name";;
		  scm/*.scm)	debugMsg "got file $name";;
		./scm/*.scm)	debugMsg "got file $name";;
		  medium/*.M)		debugMsg "got file $name";;
		./medium/*.M)		debugMsg "got file $name";;
		  small/*.S)		debugMsg "got file $name";;	
		./small/*.S)		debugMsg "got file $name";;	
		  help/*)		debugMsg "got file $name";;	
		./help/*)		debugMsg "got file $name";;	
		  files/*)		debugMsg "got file $name";;	
		./files/*)		debugMsg "got file $name";;	
		*.pim)			errorMsg "invalid file $name";ret=1;;
		*.plugin)		errorMsg "invalid file $name";ret=1;;
		*.scm)			errorMsg "invalid file $name";ret=1;;
		*.M)			errorMsg "invalid file $name";ret=1;;
		*.S)			errorMsg "invalid file $name";ret=1;;	
		*)				debugMsg "got file $name";;		# supporting files
		esac
	done
	return "$ret"
}

validpim() {
	debugMsg "validpim: $*"

	if [ $# = 0 ]
	then
		errorMsg "no file passed to pim file validation routine"
		return 1 
	fi

	archivepim="$1"
	case "$archivepim" in
	*.pim)	;;
	*)  errorMsg "Plug-in archive suffix must be .pim"; return 1;;
	esac

	valid_version "$archivepim"
	if [ "$?" -ne 0 ]
	then
		errorMsg "invalid archive version"
		return 1
	fi
	return 0
}

check_environment() {

	if [ $# -ne 1 ]
	then
		errorMsg "check_environment should only be passed one argument"
		return 1
	fi

	script_mode="$1"

	msg="The following environment variable(s) are not set: "
	foundOne=0

	if [ -z "$ALIAS_LOCATION" ]
	then
		# This case should not happen but lets program for all
		# out mayhem and disaster
		msg="$msg \$ALIAS_LOCATION"
		logErrorMsg "$msg"
		return 1
	fi 

	if [ ! -x "$ALIAS_LOCATION/bin/aliasWarning" ] 
	then
		logErrorMsg "aliasWarning binary not found"
		return 1
	fi

	if [ -z "$ALIAS_WORKENV" ]
	then
		msg="$msg \$ALIAS_WORKENV"
		errorMsg "$msg"
		return 1
	fi

	if [ -z "$HOME" ]
	then
		msg="$msg \$HOME"
		errorMsg "$msg"
		return 1
	fi

	return 0
}

readUntilChars() {

	character_read=""
	if [ $# = 0 ]
	then
		errorMsg "no character strings passed to read routine"
		return 
	fi

	notDone=0
	read AChar
	while [ "$notDone" -eq 0 ]
	do
		for paramChar in $*
		do
			if [ "$paramChar" = "$AChar" ]
			then
				character_read="$paramChar"	
				return
			fi
		done
		errorMsg "Valid responses are: $*"
		read AChar
	done	 

	return
}

restrictedRm() {

	if [ $# = 0 ]
	then
		errorMsg "no files passed to file removal routine"
		return 
	fi

	foundOne=0
	options=""
	for param in $*
	do
		case "$param" in
		*tar)	;;
		*tmp)	;;
		*pim)	;;
		-i)		options="-i" ; shift ;;
		*)		foundOne=1 ;;
		esac
		if [ "$foundOne" -ne 0 ] 
		then
			errorMsg "Questionable file name '$param' has been requested to be deleted"
			return
		fi
	done

	# remove the files
	for param in $*
	do
		rm $options $param
	done
}

#
# Tar file routines
#

build_removal_script() {
	debugMsg "build_removal_script: $*"

	if [ $# -ne 2 ]
	then
		errorMsg "build removal script routine needs 2 parameters"
		return 1
	fi

	current_plugin_path="$1"

	removal_path="$current_plugin_path/remove"

	if [ ! -d "$removal_path" ]
	then
		askYesNo "Create directory for removal scripts in '$removal_path' ?"
		if [ "$?" -eq 0 ]
		then
			return 1
		else
			mkdir "$removal_path"
		fi
	fi

	bName=`basename $2`
	removal_script="$removal_path/remove-$bName"
	temp_script="$temp_dir/remove-$bName.tmp"

	debugMsg " Removal script goes into : $removal_script"

	# check to make sure we have temp space
	check_temp_space "$temp_dir"
	if [ "$?" -ne 0 ]
	then
		return 1
	fi
	# check to make sure we have enough real space
	check_temp_space "$removal_path"
	if [ "$?" -ne 0 ]
	then
		return 1
	fi

	# set the temp files we will use 
	save_temp_file_name "$temp_script"
	save_temp_file_name "$removal_script"

	# first build a temp file that contains the file names of the archive 
	tail +"$tar_start_pos"c $2 | tar tf - > "$temp_script" 2>/dev/null
	if [ "$?" -ne 0 ]
	then
		return 1
	fi
	
	#
	# Echo the actual text of the script into the removal script
	# Note that we use Bourne shell.
	#
	echo '#!/bin/sh' 										> "$removal_script"
	echo '#' 												>> "$removal_script"
	echo 'if [ -z "$ALIAS_LOCATION" ]' 						>> "$removal_script"
	echo 'then' 											>> "$removal_script"
	echo '   echo "$ALIAS_LOCATION not set" ' 				>> "$removal_script"
	echo '   exit 1' 										>> "$removal_script"
	echo 'fi' 												>> "$removal_script"
	echo 'if [ ! -x "$ALIAS_LOCATION/bin/aliasWarning" ]' 	>> "$removal_script"
	echo 'then' 											>> "$removal_script"
	echo '   echo "aliasWarning binary not found" ' 		>> "$removal_script"
	echo '   exit 1' 										>> "$removal_script"
	echo 'fi' 												>> "$removal_script"
	echo '#' 												>> "$removal_script"
	echo 'if [ "$#" -eq 0 ] ' 								>> "$removal_script"
	echo 'then'	 											>> "$removal_script"
	sed -e \
		"s:^:    rm ${current_plugin_path}\/:" "$temp_script" \
															>> "$removal_script"	
	if [ "$?" -ne 0 ]
	then
		return 1
	fi

	echo '    echo "Finished deleting files for $0." | $ALIAS_LOCATION/bin/aliasWarning -t"Plug-in Manager" -bOK -f - ' 										>> "$removal_script"
	echo 'else' >> "$removal_script"
	sed -e \
		"s:^:    rm -i ${current_plugin_path}\/:" "$temp_script" \
															>> "$removal_script"	
	if [ "$?" -ne 0 ]
	then
		return 1
	fi

	echo 'fi' 												>> "$removal_script"

	# if there are any html files that were just installed, removed
	# them from the index.html file
	for html_file in $html_list
	do
		echo "if [ -f "$current_plugin_path/$html_index_file" ] " 	\
				>> "$removal_script"
		echo 'then'													\
				>> "$removal_script"
		echo "grep -v $html_file "$current_plugin_path/$html_index_file" > "$current_plugin_path/$html_index_file.tmp" "	\
				>> "$removal_script"
		echo "mv "$current_plugin_path/$html_index_file.tmp" "$current_plugin_path/$html_index_file" " 															\
				>> "$removal_script"
		echo "echo Removed HTML link in "$current_plugin_path/$html_index_file" for `basename $html_file` "					\
				>> "$removal_script"
		echo 'fi'													\
				>> "$removal_script"
	done

	echo 'rm $0 # remove myself' 							>> "$removal_script"

	chmod +x "$removal_script"
	restrictedRm "$temp_script"

	# no longer need to be cleaned up in case of a trap 
	remove_temp_file_name "$temp_script"
	remove_temp_file_name "$removal_script"

	return 0
}

addheader() {

	if [ $# = 0 ]
	then
		errorMsg "no files passed to add header routine"
		return
	fi

	echo "$pim_header" > $1 
}

createpim() {

	debugMsg "createpim: $*"
	if [ $# = 0 ]
	then
		errorMsg "no files passed to pim file creation routine"
		return
	fi

	archiveName=`basename $1 .pim`
	archivepim="`dirname $1`/$archiveName.pim"
	archivetar="$temp_dir/$archiveName.tar"
	shift

	# check to make sure we have temp space
	check_temp_space "$temp_dir"
	if [ "$?" -ne 0 ]
	then
		return 1
	fi
	
	save_temp_file_name "$archivetar"

	createtar "$archivetar" $*
	if [ "$?" -ne 0 ]
	then
		errorMsg "could not create tar file"
		return
	fi

	tartopim "$archivetar" "$archivepim"

	restrictedRm "$archivetar"

	remove_temp_file_name "$archivetar"
}

appendpim() {
	debugMsg "appendpim: $*"
	if [ $# = 0 ]
	then
		errorMsg "no files passed to pim file creation routine"
		return
	fi

	archiveName=`basename $1 .pim`
	archivepim="`dirname $1`/$archiveName.pim"
	archivetar="$temp_dir/$archiveName.tar"
	shift

	save_temp_file_name "$archivetar"

	# extract, append , recreate pim	
	tail +"$tar_start_pos"c "$archivepim" > "$archivetar"

	tar -rvf $archivetar $*
	if [ "$?" -ne 0 ]
	then
		return
	fi

	tartopim "$archivetar" "$archivepim"
	restrictedRm "$archivetar"

	remove_temp_file_name "$archivetar"
}

pimtotar() {
	debugMsg "pimtotar: $*"
	if [ $# -ne 1 ]
	then
		errorMsg "incorrect number of files passed to pimtotar"
		return 1
	fi
	tail +"$tar_start_pos"c $1 | tar xvof -
	return "$?"
}

tartopim() {
	debugMsg "tartopim: $*"
	if [ $# -ne 2 ]
	then
		errorMsg "incorrect number of files passed to tartopim"
		return
	fi

	archivetar="$1"
	archivepim="$2"
	addheader "$archivepim"
	cat "$archivetar" >> "$archivepim"
}

createtar() {
	debugMsg "createtar: $*"
	if [ $# -lt 2 ]
	then
		errorMsg "tar creation routine needs at least 2 parameters"
		return
	fi

	archivetar="$1"
	shift

#	check_file_space "$archivetar" .         
#	if [ "$?" -ne 0 ]
#	then
#		return
#	fi

	tar -cvf $archivetar $*
	return "$?"
}

extractor() {
	( 
	cd "$plugin_path"
	ret=0
	for file_name in $file_list
	do
		if [ -f "$file_name" ]
		then
			askContinueAbort "Warning: File '$file_name' of the archive already exists.  Continue or Abort?"
			if [ "$?" -eq 0 ]
			then
				ret=2
				break
			fi
		fi
	done
	if [ "$ret" -eq 0 ]
	then
		check_file_space $pimfile .
		if [ "$?" -ne 0 ]
		then
			ret=1
		fi	
	fi
	if [ "$ret" -eq 0 ]
	then	
		tail +"$tar_start_pos"c $pimfile | tar xvof -     
		if [ "$?" -ne 0 ]
		then
			ret=1
		fi
	fi
	return $ret 
	)
	return "$?"
}

extracttar() {
	debugMsg "extracttar: $*"
	if [ $# = 0 ]
	then
		errorMsg "no file passed to pim file extraction routine"
		return
	fi
	
	pimfile="$1"

	case $pimfile in
	/*) ;;
	*) pimfile=`pwd`/$pimfile
	esac

	if [ ! -f "$pimfile" ]
	then
		errorMsg "File '$pimfile' cannot be extracted since it does not exist"
		return
	fi

	if [ ! -d "$plugin_path" ]
	then
		errorMsg "Plug-in directory '$plugin_path' does not exist"
		return 1
	fi



	# get the file list
	file_list=`tail +"$tar_start_pos"c $pimfile | tar tf - 2>/dev/null`
	html_list=""

	extractor
	result="$?"

#	Leaving this functionality out for this release.
#	if [ "$result" -eq 0 ]
#	then
#		for file_name in $file_list
#		do
#			case "$file_name" in
#			*.html) 
#				html_list="$html_list $plugin_path/$file_name" 
#				build_html_index `basename $pimfile` "$plugin_path/$file_name" ;;
#			esac
#		done
#	fi

	return 0
}

viewpim() {
	for pimfile in $*
	do
		blankLine
		infoMsg "View plug-in archive information for '$pimfile'"

		if [ ! -f "$pimfile" ]
		then
			errorMsg "File '$pimfile' does not exist"
			return
		fi

		validpim "$pimfile"
		if [ "$?" -eq 0 ]
		then
			tail +"$tar_start_pos"c $pimfile | tar tf - 2>/dev/null
		fi
	done
}

install_all() {

	for pimfile in $*
	do
		blankLine
		infoMsg "Installing plug-in archive '$pimfile'"

		validpim "$pimfile"
		if [ "$?" -eq 0 ]
		then
			if [ ! -f "$pimfile" ]
			then
				errorMsg "File '$pimfile' does not exist"
				return
			fi
			extracttar "$pimfile"
			ret="$?"
			if [ "$ret" -ne 0 ]
			then
				if [ "$ret" -eq 2 ] # person aborted
				then
					return
				else
					askYesNo "Error extracting file, do you wish to continue?"
					if [ "$?" -eq 0 ]
					then
						return 
					fi
				fi
			else
				build_removal_script "$plugin_path" "$pimfile"
				if [ "$?" -ne 0 ]
				then
					askYesNo "Error building removal script, do you wish to continue?"
					if [ "$?" -eq 0 ]
					then
						return
					fi
				fi
			fi
		else
			return
		fi
	done

	promptOK "Installation complete."
}

runremovescript() {
	debugMsg "runremovescript : $*"

	if [ $# = 0 ]
	then
		errorMsg "no files passed to pim file removal routine"
		return
	fi

	for pimfile in $*
	do
		blankLine
		infoMsg "Removing plug-in archive files for '$pimfile'"

		case $pimfile in
		/*) # should not be a full pathname 
			errorMsg "Full pathnames specified for plug-in archive"
			return
			;;
		esac

		file_to_delete="$plugin_path/remove/remove-$pimfile"
		debugMsg " remove script to run : $file_to_delete"
		if [ -f "$file_to_delete" ]
		then
			# give it a parameter so it does not perform a gui delete
			/bin/sh "$file_to_delete" "-commandLine"
			if [ "$?" -ne 0 ]
			then
				errorMsg "failed to run remove script for '$pimfile'"     
				return
			fi
		else
			errorMsg "Removal script for plug-in archive file '$pimfile' does not exist"
			return
		fi
	done
}

promptlocal_or_global() {

	if [ $# -ne 1 ] 
	then
		errorMsg "prompting routine needs one parameter"
		return 1
	fi

	prompt_msg="$1"

	askLocalGlobal "$prompt_msg"

	if [ "$?" -eq 1 ]
	then
		plugin_path="$local_plugin_path"
	else
		plugin_path="$global_plugin_path"
	fi

	infoMsg "Current plug-in path is '$plugin_path'."

	if [ ! -d "$plugin_path" ]
	then
		errorMsg "Plug-in directory '$plugin_path' does not exists"
		return 1
	fi
	if [ ! -w "$plugin_path" ]
	then
		errorMsg "Plug-in directory '$plugin_path' is not writeable by `whoami`"
		return 1
	fi

	return 0
}

# 
# Wrapper functions for the command line options
#

pim_install() {
	debugMsg "pim_install: $*" 

	blankLine
	infoMsg "Plug-in archive installation : $* "

	if [ "$gui_mode" -eq 1 ]
	then
		 plugin_path="$local_plugin_path"
	else
		promptlocal_or_global "Do you want to install the plug-in module in the local or global directory"
		if [ "$?" -ne 0 ] 
		then
			return
		fi
	fi 
	
	install_all $*
}

pim_remove() {
	debugMsg "pim_remove: $*" 

	blankLine
	infoMsg "Plug-in archive removal : $*"

	promptlocal_or_global "Do you want to remove a local or global plug-in module"
	if [ "$?" -ne 0 ] 
	then
		return
	fi

	runremovescript $*	
}

pim_createpim() {
	debugMsg "pim_createpim: $*"

	if [ $# = 0 ]
	then
		errorMsg "no archive files specified"
		return
	fi 

	archiveName="$1"

	blankLine 
	infoMsg "Creating plug-in archive file '$archiveName'"

	# if we are creating this file, it should not be there already
	if [ -f "$archiveName" ] 
	then
		errorMsg "File '$archiveName' already exists"  
		return
	fi
	shift 

	# only take relative files
	relpath $*
	if [ "$?" -ne 0 ]
	then
		errorMsg "Absolute path name passed in or file not below the current directory"
		return
	fi

	# is our input valid files
	validfiles $*
	if [ "$?" -ne 0 ]
	then
		return
	fi

	# build the plug-in archive file
	createpim "$archiveName" $*
}

pim_createpimfromdir() {
	debugMsg "pim_createpimfromdir: $*"
	
	if [ $# -ne 2 ]
	then
		errorMsg "pim creation from dir routine needs 2 parameters"
		return
	fi 

	archiveName="$1"
	fromdir="$2"

	blankLine 
	infoMsg "Creating plug-in archive file '$archiveName' from directory '$fromdir'"

	if [ ! -d "$fromdir" ]
	then
		errorMsg "'$fromdir' is not a directory"
		return
	fi

	case $archiveName in
	/*) ;;
	*)	archiveName="`pwd`/$archiveName"
	esac

	( cd $fromdir
	dirfiles=""
	filesanddirs=`ls .`
	for fName in $filesanddirs
	do
		if [ -d "$fName" ]
		then
			dirfiles="$dirfiles `ls ./$fName/*`"
		else
			dirfiles="$dirfiles $fName"	
		fi	
	done
	pim_createpim $archiveName $dirfiles
	)
}

pim_appendpim() {
	debugMsg "pim_appendpim: $*"

	archiveName="$1"

	blankLine 
	infoMsg "Appending plug-in archive file '$archiveName'"

	# make sure it exists before we append to it 
	if [ ! -f "$archiveName" ]
	then
		errorMsg "File '$archiveName' does not exist"
		return
	fi
	shift

	if [ $# = 0 ]
	then
		errorMsg "no archive files specified"
		return
	fi 

	# only take relative files
	relpath $*
	if [ "$?" -ne 0 ] 
	then
		errorMsg "Absolute path name passed in or file not below the current directory"
		return
	fi

	# is our input valid files
	validfiles $*
	if [ "$?" -ne 0 ]
	then
		return
	fi

	appendpim "$archiveName" $*
}

pim_view() {
	debugMsg "pim_view : $*"

	blankLine 
	infoMsg "View plug-in archive file '$*'"

	viewpim $*
}

#
# Help
#
pim_help() {

	echo
	echo 'The Plug-in Manager Shell script supports the following options:'
	echo
	echo '	-install <pim file, pim file, ... >'
	echo '		Used for local or global installation of plug-in archive files'
	echo '	-remove  <pim file, pim file, ... >'
	echo '		Used to remove plug-in archive files'
	echo ' 	-view <pim file, pim file, ... >'
	echo '		View the files within a plug-in archive'
	echo ' 	-create  <pim file> <plug-in files> <scheme files> <icon files> <other files> '
	echo '		Allows for the creation of plug-in archive files'
	echo '		NOTE: the archives files must be in the following '      
	echo '		relative directories:'
	echo '		*.plugin in 	./lib'
	echo '		*.scm in 		./scm'
	echo '		*.M in 			./medium'
	echo '		*.S in 			./small'
	echo '		Files other than the above which are a part of the plug-in'
	echo '		archive  should be stored in the current directory.'
	echo ' 	-cR  <pim file> <plug-in file directory> '
	echo '		Recursive creation  of a plug-in archive from a directory'
	echo '		NOTE: the directory must have the same structure as outlined'
	echo '		in the -create option'
	echo '	-append  <pim file> <plug-in files> <scheme files> <icon files>'
	echo '		Appends to an already created plug-in archive file'
	echo '		NOTE: the directory must have the same structure as outlined'
	echo '		in the -create option' 
	echo '	-gui_install  <pim file, pim file, ... >'
	echo '		Installs plug-in archive files through the desktop'
	echo '	-h'
	echo '		Help'
	echo
	echo 'Short forms such as -i,-r,-v can be used instead of the full command'
	echo 'name.'
	echo ' '
#	Leaving the html functionality out for this release.
#	echo 'If a plug-in archive is installed that contains a .html file, a web'
#	echo 'page is generated(if its not already there) in the local or global'
#	echo 'plug-in directories(depending on the type of installation chosen).'
#	echo 'A link is added to the page that points to the just installed html file.'
#	echo "The web page is called '$html_index_file'."
#	echo ' '
	echo 'Plug-ins installed locally go into $HOME/.Alias/plugins and plug-ins'
	echo 'installed globally go into $ALIAS_LOCATION/ODS/OpenAlias/plugins.'
	echo 

}

#
# Main line code
#

main() { 
	debugMsg " "
	debugMsg "MAIN: $*"

	# do we have any parameters
	if [ $# -eq 0 ]
	then
		errorMsg "no parameters"
		return
	fi	
	
	check_environment "$1"
	if [ "$?" -ne 0 ]
	then
		return
	fi
	set_variables
	set_trap

	# options
	case "$1" in
	-a*)		shift; pim_appendpim 	$*;;
	-cR)		shift; pim_createpimfromdir $* ;;
	-c*)		shift; pim_createpim 	$*;;
	-gui*)		shift; gui_mode=1 ; pim_install $*;;
	-h*)		pim_help				  ;;
	-i*)		shift; pim_install 		$*;;
	-r*)		shift; pim_remove 		$*;;
	-t) ;;
	-v*)		shift; pim_view			$*;;
	*)			errorMsg "unknown option '$1'" ;;	
	esac			

}

# Call the main procedure

# ibm sh "$*" bug
if [ -z "$*" ]
then
    main
else
    main $*
fi
