#!/bin/sh
# ############################################################################
#                                                                            #
#      Copyright (C) 1985, 1986, 1987, 1990, 1994  Alias Research, Inc.      #
#                                                                            #
#    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. #
#                                                                            #
# ############################################################################
#
# $Source: /usr/u/pearce/v6/Alias/RCS/renderit.sh_sgi,v $ $Revision: 6.6 $
# $Author: pearce $ $Date: 96/04/10 09:00:51 $
#
# Renderit.sh --
#
#       The purpose of this is to actually execute the rendering code.
#	It copies files to the proper locations and if necessary starts
#	the renderit script on a remote machine
#
#	Usage:
#
#	renderit [-r renderer] [-n num_procs] [-t targ] [-e engine:loc] [-f pixfile] [sdlfile]
#
#	If the -t option is missing the rendered image(s) are left where they
#	were rendered. If the -e option is missing, rendering is done on the
#	local host in the current directory. The -r option indicates the
#	program to invoke to do	the rendering (this is renderer by default).
#	targ can be in host:pathname format. If sdlfile is missing then we
#	get the sdlfile	from the standard input in which case you will
#	probably need the -f option to indicate the name of the resulting
#	pix files.
#
#	There are a few places in here where the standard ALIAS layout
#	of projects is assumed. This is unfortunate but necessary to
#	make things work with ALIAS. The major assumption is that the
#	renderer will be running in a project directory (or at least a
#	directory with a pix directory)


renderer="renderer"
programname=`basename $0`
tempfile=/usr/tmp/renderit.$$
tempsdl1=/usr/tmp/sdl1.$$
tempsdl2=/usr/tmp/sdl2.$$

#
# various system programs we use - do this so that we don't run into other
# similarily named programs in the user's search path
#
RSH=/usr/bsd/rsh
RM=/bin/rm
CAT=/bin/cat
EXPR=/bin/expr
CP=/bin/cp
CPP=/lib/cpp
RCP=/usr/bsd/rcp
TOUCH=/bin/touch
TEE=/bin/tee
EGREP=/usr/bin/egrep
AWK=/usr/bin/awk
BASENAME=/bin/basename
PWD=/bin/pwd

help()
{
	$CAT << EOF
PURPOSE:   render (or raytrace) the supplied ALIAS SDL file
USAGE:     $programname [-r <str>] [-e <str>] [-t <str>] <sdlfile>
FLAGS:
-r <str>   use <str> as the rendering program (default: renderer)
-e <str>   <str> is of the form <host>:<location> where <host> is the name
           of the rendering engine and <location> is the directory in which
           to do the rendering. If <host> is omitted, rendering occurs on the
           local host. If <location> is a relative pathname (no leading /),
           it is relative to the user's home directory on <host>. If
           <location> is omitted, rendering occurs in the user's home
           directory on <host>. If the -e option is not given rendering
           occurs on the local host in the current directory.
-t <str>   <str> is the pathname of the directory where the resulting pix
           file(s) are moved. If <str> is a relative pathname, it is
           relative to the current directory. If the -t option is omitted
           the pix file(s) generated by the rendering program are not moved.
<sdlfile>  specifies the SDL file to render
EOF
}

#
# define cleanup function
#
cleanup()
{
	$RM -f $tempfile $tempsdl1 $tempsdl2
	if [ "$deleteSDL" = "-z" ]; then
		$RM -f $original_sdlfile
    fi
}

#
# setup some traps
#
trap "cleanup; exit 1" 1 2 3 15

#
# define error function
# - the errorflag is used when remote rendering to determine if error occurred
#
warningflag="WARNING:"
errorflag="ERROR:"
helpmsg="PURPOSE:"
error()
{
	echo ${programname}@`hostname` $errorflag $1 1>&2
	cleanup
	exit 1
}
warning()
{
	echo ${programname}@`hostname` $warningflag $1 1>&2
}

if [ "$1" = "-" ]; then
	help
	exit 0
fi

numprocs=""
while getopts Al:n:t:e:r:f:z arg
do
	case $arg in
	A)	aliasinvoked="-A" ;;
	t)	targetdir="$OPTARG" ;;
	e)	remotespec="$OPTARG" ;;
	n)  numprocs="-n $OPTARG" ;;
	r)	renderer="$OPTARG" ;;
	z)  deleteSDL="-z" ;;
	f)	picturefile="$OPTARG" ;;
	\?)
		error "invalid option -$arg" ;;
	esac
done

#
#	shift past all options
#
shift `$EXPR $OPTIND - 1`

if [ $# -gt 1 ]; then
	error \
"Usage:\\n$programname [-r renderer] [-t target] [-e host:loc] sdlfile"
fi

sdlfile=$1
original_sdlfile=$1
if [ ! "$picturefile" ]; then
	if [ "$sdlfile" ]; then
		picturefile=`$BASENAME $sdlfile`
	else
		error "could not determine picture filename, use -f option"
	fi
fi

if [ "$remotespec" ]; then
	# expr blows up if the only thing in remotespec is a colon
	if [ "$remotespec" != ":" ]; then
		if $EXPR "$remotespec" : '.*:.*' > /dev/null; then
			renderengine=`$EXPR "$remotespec" : '\(.*\):.*'`
			renderlocation=`$EXPR "$remotespec" : '.*:\(.*\)'`
		else
			renderengine=$remotespec
		fi
	fi
fi

if [ -z "$renderengine" -o "$renderengine" = `hostname` \
						-o "$renderengine" = "localhost" ]; then
	islocal="true"
fi

#
# make target dir absolute pathname if necessary
#
if [ "$targetdir" ]; then
	if $EXPR "$targetdir" : '.*:.*' > /dev/null; then
		:
	elif $EXPR "$targetdir" : '[^/].*' > /dev/null; then
		targetdir=`$PWD`/$targetdir
	fi
fi

#
# make copy of sdl, so that it can't be changed from under us
# - if sdlfile is empty we are reading from stdin
#
if [ "$sdlfile" ]; then
   	if test "$aliasinvoked" != ""; then
        :
	else
		if $CP $sdlfile $tempsdl1; then
			if $CPP -C -P $tempsdl1 $tempsdl2; then
				sdlfile=$tempsdl2
			else
				error "preprocessing of $sdlfile failed"
			fi
		else
			error "could not read sdl file \"$sdlfile\""
		fi
	fi
fi

#
# first move to the designated directory
# - the rendering directory is relative to the home directory
#
if [ "$islocal" -a "$remotespec" ]; then
	cd
	if [ "$renderlocation" ]; then
		if [ -d "$renderlocation" ]; then
			cd $renderlocation
		else
			error "could not change to $renderlocation directory"
		fi
	fi
fi
# this umask is here, because it was here in the old renderit script
umask 0

#
#	do the rendering
#	- if we are local we can just go ahead and do it
#	- if remote we rsh another renderit script on the remote host
#
if [ "$islocal" ]; then
	#
	# decide where to put the stupid out.<filename> file
	# - if there is an SDL directory in the current directory put it there
	#   otherwise leave it in current directory
	#
	outfile=out.$picturefile
	if [ -d sdl ]; then
		outfile=sdl/$outfile
	fi

	#
	# start the renderer of choice and let it know if ALIAS started it
	#
	if $renderer $numprocs $aliasinvoked $sdlfile > $outfile; then
		if [ "$targetdir" ]; then
			#
			# determine if target directory is on a different machine
			#
			if $EXPR "$targetdir" : '.*:.*' > /dev/null; then
				command="$RCP"
				remote="$RSH `$EXPR $targetdir : '\(.*\):.*'`"
				probedir=`$EXPR "$targetdir" : '.*:\(.*\)'`
			else
				command="$CP"
				remote=""
				probedir="$targetdir"
			fi

			#
			# it is possible that $targetdir is the same directory as pix
			# this is a little trick to figure that out
			#
			probefile=probe.$$
			err=`$remote $TOUCH $probedir/$probefile 2>&1`
			if [ $? -ne 0 -o "$err" ]; then
				error "could not write to $targetdir"
			fi

			# if the probefile turned up in pix directory, we don't have
			# to copy files because the pix directory and targetdir
			# are the same.
			if [ ! -f pix/$probefile ]; then
				$remote $RM $probedir/$probefile

				# examine the outfile to see what files we produced
				# and copy these back
				$AWK '$1 ~ /^Completed/ { print $2 }' $outfile | while read fname
				do
					case $fname in
					mask*)	if $command $fname $targetdir/../mask; then
							$RM $fname
						fi ;;
					*)	if $command $fname $targetdir; then
							$RM $fname
						fi ;;
					esac
				done
				# try to copy the outfile into an sdl directory which
				# is hopefully under the parent directory of the target
				# directory - if this fails don't shed any tears
				if $command $outfile ${targetdir}/../sdl; then
					$RM $outfile
				fi
			else
				$RM pix/$probefile
			fi
		fi
	else
        status=$?
		if [ $status -eq 139 ]; then
            error "$renderer exited due to: segmentation fault (error code $status)"
		else
            if [ $status -eq 144 ]; then
                    error "$renderer exited due to: not enough memory (error code $status)"
            else
        		if [ $status -eq 138 ]; then
                    error "$renderer exited due to: bus error (error code $status)"
        		else
               		if [ $status -eq 143 ]; then
                        error "$renderer exited due to: user's request (error code $status)"
                    else
                       	error "$renderer exited with exit code $status"
                    fi
                fi
			fi
		fi
	fi
else
	#
	# make a quick check for accessibility of remote host. Along with
	# checking accessibility, this code determines if a remote render
	# can be performed by testing if the renderit script can be found
	# on the rendering ehgine. If the Alias software has been installed
	# on the rendering engine and the user's search path on the rendering
	# engine is "correct", when this script executes `renderit -' on the
	# rendering engine, it should generate a help message of which the
	# string "PURPOSE:" is part of. If the output of a successful rsh
	# does not contain the string "PURPOSE:", renderit was not found
	# on the render engine and the render cannot proceed.
	#
	if test "$ALIAS_LOCATION" != ""; then
		AL="ALIAS_LOCATION=$ALIAS_LOCATION"
	else
		AL=""
	fi
	if $RSH $renderengine "/bin/sh -c 'PATH=$PATH $AL $programname -'" > $tempfile 2>&1; then
		# verify that the help message is in the tempfile after the
		# rsh is complete. If part of the message is not in the file,
		# generate an error message and exit.
		if $EGREP -s "^$helpmsg" $tempfile; then
		:
		else
			error "cannot find $programname on $renderengine"
		fi
		if [ "$targetdir" ]; then
			if $EXPR "$targetdir" : '.*:.*' > /dev/null; then
				targetdir="-t $targetdir"
			else
				targetdir="-t `hostname`:$targetdir"
			fi
		fi

		#
		# start renderit on remote host and collect stderr which is examined
		# after rsh is finished. This is done because rsh doesn't return exit
		# code of the remote renderit script. If the errorflag is detected
		# an error occurred
		# - send the sdlfile via standard input to get around the hassles of
		#   copying it to the right place
		#
		# NB: quoting is very significant here -- know sh rules!
		#	especially single quotes have no significance inside "
		if $RSH $renderengine "/bin/sh -c \"PATH=$PATH $AL $programname \
			-r $renderer -e ':$renderlocation' -f $picturefile \
			$targetdir $numprocs $aliasinvoked\"" < $sdlfile 2>&1 \
			| $TEE $tempfile 1>&2
		then
			#
			# exit with an error if there were any error messages
			#
			if $EGREP -s $errorflag $tempfile; then
				error "remote render on $renderengine exited abnormally"
			fi
		else
			error "error running $programname on host \"$renderengine\""
		fi
	else
		error "couldn't contact the render engine \"$renderengine\""
	fi
fi

cleanup
exit 0
