#!/bin/ash
# *********************************************************************
# tmptable: NoSQL temporary table creator.
# Copyright (c) 2001,2006 Carlo Strozzi
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 dated June, 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# *********************************************************************
# $Id: tmptable,v 1.7 2006/03/10 11:26:13 carlo Exp $

# Get local settings and apply defaults.
: ${NOSQL_INSTALL:=/usr/local/nosql} ${TMPDIR:=/tmp} ${rm_delay:=10}

while [ $# -gt 0 ]
do
   case $1 in
	-h|--help)
	     grep -v '^#' $NOSQL_INSTALL/help/tmptable.txt
	     exit 1
	;;
	--show-copying)
	     cat $NOSQL_INSTALL/doc/COPYING
	     exit 1
	;;
	--show-warranty)
	     cat $NOSQL_INSTALL/doc/WARRANTY
	     exit 1
	;;
	-n|--no-trap)	no_trap=1 ;;
	-i|--input)	shift; i_file="$1" ;;
	-o|--output)	shift; o_file="$1" ;;
	-d|--delete)	shift; rm_delay="$1" ;;
   esac
   shift
done

if [ "$i_file" = "" ]
then
   i_file=-
else
   exec < "$i_file"
fi

if [ "$o_file" = "" ]
then
   o_file=`mktemp $TMPDIR/nosql.XXXXXX` || exit $?
   # Set-up trapping on signals other than "0".
   trap "rm -f $o_file" 1 2 3 15
else
   # Do not trap an externally provided temporary file. It will be
   # up to the caller to decide what to do with it.
   no_trap=1
fi

# In any case we need file descriptor "2" for printing the file-name.
exec 3> "$o_file"

cat $i_file >&3

if [ $? != 0 ]
then
   # Print a filename to stdout even in case of errors.
   o_file=/dev/null
fi

echo $o_file

# I cannot simply remove the temporary file on exit, or it will not
# be available to the other programs that are usually run on the same
# pipeline along with this one. If stdout is not redirected, then the
# background command will use the one of the parent shell, and the
# latter will remain "appended" for the duration of the delay.

if [ "$no_trap" = "" ]
then
   (sleep $rm_delay; rm -f $o_file) >/dev/null &
   exit $?
fi

# End of program.
