:
#
# zeroexit	-- Run a command but trash the exit status
#
# Copyright (c) 1989, 1990, The Santa Cruz Operation, Inc.,
# and SecureWare, Inc.  All rights reserved.
#
# This Module contains Proprietary Information of the Santa Cruz
# Operation, Inc., and SecureWare, Inc., and should be treated
# as Confidential. 
#
# Usage: zeroexit [-c] [-ieo file] cmd [args]...
#
# where -i specifies the standard input, -o the standard output,
# and -e the standard error ouput (all of which are inhierated by
# default).  Note that the <cmd> must be an absolute pathname.
#
# If -c is specified, the standard error output of <cmd> is sent
# to the standard output of <cmd>.  At the most, only one of -c
# and -e may be specified.
#

PATH=/bin:/usr/bin

#
# usage		-- Print the "usage" message
#
usage() {
	[ $# -ge 1 ] && echo "$@" >&2
	echo "Usage: $0 [-c] [-ioe file] cmd [args]..." >&2
	exit 2
}
readonly usage

#
# fatal		-- Print an error message and exit with a non-0 (failure) code
#
fatal() {
	echo "$@" >&2
	exit 1
}
readonly fatal

#
# Parse the optional flags.  The -z tests catch empty (zero-length)
# file name arguments, which would otherwise behave the same as not
# specifying the corresponding flag.  (The getopts builtin catches
# not specifying the argument at all in the first place.)
#
ifile=
ofile=
efile=
cflag=NO
while getopts i:o:e:c option; do
	case $option in
	i)	[ -z "$OPTARG" ] && usage Empty input file name
		ifile=$OPTARG
		;;
	o)	[ -z "$OPTARG" ] && usage Empty output file name
		ofile=$OPTARG
		;;
	e)	[ -z "$OPTARG" ] && usage Empty error output file name
		efile=$OPTARG
		;;
	c)	cflag=YES
		;;
	*)	usage
		;;
	esac
done

[ -n "$efile" -a $cflag = YES ] && usage At most one of -c and -e may be specified

#
# Get the command name (which must be specified); it must
# be the an absolute path of an executable regular file.
#
shift `expr $OPTIND - 1`
[ $# -le 0 ] && usage Missing absolute path of command to run
cmd=$1
shift
case $cmd in
/*)	[ -f "$cmd" -a -x "$cmd" ] || fatal Cannot execute: "$cmd"
	;;
*)	fatal Not an absolute path: "$cmd"
	;;
esac

#
# Open up any specified input or output files.  The fatal's are not
# really necessary, as the Bourne shell exits on failed exec's, but
# they do not hurt anything.
#
[ -n "$ifile" ] && {
	exec < "$ifile" || fatal Cannot open input: "$ifile"
}
[ -n "$ofile" ] && {
	exec > "$ofile" || fatal Cannot open output: "$ofile"
}
if [ -n "$efile" ]; then
	exec 2> "$efile" || fatal Cannot open error output: "$efile"
elif [ $cflag = YES ]; then
	exec 2>&1 || fatal Cannot redirect error output to standard output
fi

#
# Now run the command, being careful to pass it only the
# specified arguments.  Then (the point of this script),
# always successfully exit.
#
"$cmd" ${1+"$@"}
exit 0
