#
# bgrun.sh/bgrun2.sh (linked):
#   Run a process in the background. 
#
# Written by Leor Zolman, 7/90
#   
# Formal usage:
#   bgrun.sh outfile [ -l lockfile ]
#   bgrun2.sh outfile [ -l lockfile ] 2>errorfile
# 
# Takes script to be executed from standard input. 
#   bgrun.sh: stdout and stderr written to outfile.
#   bgrun2.sh: stdout written to outfile, stderr passed through (to errorfile)
#
# If BGTEST environment variable is "Y", creates the script file in
# the current directory for debugging and does not remove it after execution.
#
# example:
#
#   bgrun.sh /tmp/output <<END
#       echo this is a test of background processing
#       l
#       echo this is the end.
#   END
#
# WARNING!!!!! Remember to escape special characters ( $, `) that
#              must be interpreted in the background scripts!
#

if [ "$BGTEST" = Y ]; then
    debug=Y
else
    debug=N
fi

if [ $# -ne 1 -a $# -ne 3 ]; then       # check for proper usage
    echo usage: $0 outfile  [-l lockfile]
    exit
fi

trap "rm $script; exit 1" 1 2 3 9 14 15

if [ $debug = Y ]; then
    script=script                       # debug script in current directory
else
    script=`tmpname bg`                 # place script in /tmp diretory
fi

if [ $# -eq 3 ]; then           
    case $2 in
      -l|-L)
        echo "trap \"rm $script; rm $3; exit 1\" 1 2 3 9 14 15" >$script;;
      *)
        echo "usage: $0 outfile  [-l lockfile]"
        exit 1;;
    esac
else
    echo "trap \"rm $script; exit 1\" 1 2 3 9 14 15" >$script       
fi          

cat >>$script                           # copy std input into the script file

[ $debug = N ] && cat >>$script <<-END  # and append a "self-destruct" to
    rm $script                          # remove the script after execution
END
chmod +x $script                        # make the script executable 

[ -f $1 ] && rm $1                      # erase old output file, if any

cat </dev/null >$1                      # ensure output file is writeable
chmod 666 $1                            # (i.e., erasable) by everyone, to
                                        # allow public output files

unset redirerr
[ $0 = bgrun.sh ] && redirerr="2>&1"    # If bgrun.sh, direct stderr to stdout
nohup $script >>$1 $redirerr &          # execute script (immune to hangup)
