########################################################################
# File:      winterm
# Creator:   Matt Bogosian <mbogosian@usa.net>
# Copyright: (c)1997, Matt Bogosian. All rights reserved.
# Description: Shell script to act as a wrapper for Terminal to allow
#     for indicating the desired settings file from the command line.
#     There's still some iffiness on concurrency, but it's just a shell
#     program :) (there should be any problems with normal usage).
# 
#     winterm requires bash version 2 or later (or any version which
#     has the built-in "getopts" command).
# ID:        $Id: winterm,v 1.7 1998/07/21 18:56:25 mattb Exp $
# Conventions:
#     Constants - all uppercase letters with words separated by
#         underscores.
#         (E.G., MY_DEFINE=16).
#     Variables - begin with a lowercase letter followed by lowercase
#         words separated by underscores.
#         (E.G., my_local=16).
#     Functions - begin with an lowercase letter followed by lowercase
#         words separated by uppercase letters.
#         (E.G., function myFunction).
########################################################################

# Constants
NO_ERR='0'
ERR_BAD_CMD='-1'
ERR_BAD_SHELL='-2'
MIN_SHELL_VERS='2'

prog_name="${0##*/}"

# Check for the right version of bash
if [ -z "${BASH_VERSION}" ] || ! type getopts >/dev/null 2>/dev/null ; then
	echo "${prog_name} requires bash version ${MIN_SHELL_VERS} or later"
	exit "${ERR_BAD_SHELL}"
fi

# Check command-line arguments
while getopts ":f:t:" opt; do
	case "${opt}" in
		f )	SETTINGS_FILE="${OPTARG}"
		;;
		t )	WIN_TITLE="${OPTARG}"
		;;
		* )	echo "Usage: ${prog_name} [-f PREFSFILE] [-t TITLE] [CMD]"
			exit "${ERR_BAD_CMD}"
	esac
done

shift $(($OPTIND - 1))

# Set up the settings file
if [ ! -z "${SETTINGS_FILE}" ] ; then
	if [ -f "${HOME}"/config/settings/Terminal ] ; then
		# Move the original file to a temporay location first
		if [ ! -f "${HOME}"/config/settings/winterm.temp ] ; then
			mv "${HOME}"/config/settings/Terminal "${HOME}"/config/settings/winterm.temp &>/dev/null
		fi
		
		cp -dp "${SETTINGS_FILE}" "${HOME}"/config/settings/Terminal &>/dev/null
	else
		echo "${prog_name}: no such file \"${SETTINGS_FILE}\""
		exit "${ERR_BAD_CMD}"
	fi
# Make sure we're dealing with the original settings file
else
	if [ -f "${HOME}"/config/settings/winterm.temp ] ; then
		mv "${HOME}"/config/settings/winterm.temp "${HOME}"/config/settings/Terminal &>/dev/null
	fi
fi

# Start the terminal
if [ -z "${WIN_TITLE}" ] ; then
	Terminal "${@}"
else
	Terminal -t "${WIN_TITLE}" "${@}"
fi

# Move the original file back when we're done
if [ ! -z "${SETTINGS_FILE}" ] && [ -f "${HOME}"/config/settings/winterm.temp ] ; then
	mv "${HOME}"/config/settings/winterm.temp "${HOME}"/config/settings/Terminal &>/dev/null
fi

exit "${NO_ERR}"
