#!/bin/sh
#
# Allows safe in-place replacement of a NoSQL table.
#

RCS_ID='$Id: nsq-tee,v 1.1 1998/03/09 21:28:21 carlos Exp $'


my_name=$(basename $0)

while [ $# -ge 1 ] ; do
  case $1 in
	-h*) cat <<_EOH_

        NoSQL operator: ${my_name}

Usage:  ${my_name}  [options]  output_table

Options:
    -b    Take a preventive backup copy of a pre-existing
          "output_table" with the same name.
    -s    Suppress writing the table to STDOUT.
    -h    Print this help info.
    -N    Do not lock output table (use with caution).

It can be safely used in constructs like :

    nsq-compute ... < table.rdb | nsq-tee table.rdb | ...

without worring that the original input file table.rdb
be destroyed before the pipeline has completed.

This operator reads an rdbtable via STDIN and produces the same
rdbtable on STDOUT, [over]writing the rdbtable "output_table"
given as a command line argument. It's function is similar to 
that of the UNIX utility 'tee'.

$RCS_ID

			----------------------
NoSQL RDBMS, Copyright (C) 1998 Carlo Strozzi.
This program comes with ABSOLUTELY NO WARRANTY; for details
refer to the GNU General Public License.

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.
			----------------------

_EOH_
		exit 0
		;;
	-b) shift; do_backup=1		;;
	-s) shift; no_stdout=1		;;
	-N) shift; no_lock=1		;;
	*)  out_tbl=$1; break		;;
  esac
done

# Prevent possible clobbering of backup table.

case ${out_tbl} in
  ""|-*)
	echo -e "\nUsage: ${my_name} [-b] output_table\n" >&2
	exit 1
	;;
  ,*)
	echo -e "\nTable name may not start with ','\n" >&2
	exit 2
	;;
esac

out_tbl=$(basename $1)
out_dir=$(dirname $1)

# Use system-wide lock directory if specified in env.

if [ -z "$NSQLOCKS" ]
then
	lock_stem="${out_dir}/"
else
	lock_stem="$NSQLOCKS/"
fi

[ "${no_lock}" = 1 ] || lock_list="${lock_stem}${out_tbl}.LCK"

if [ "${do_backup}" ]; then
	lock_list="${lock_list} ${lock_stem},${out_tbl}.LCK"
fi

trap_list=${lock_list}

tmp_file=${TMPDIR:-/tmp}/${my_name}.t.$$

# Call external table-locking program. 
if [ "${lock_list}" ]; then
	${NSQLOCKER:-nsq-lock} ${lock_list} || exit 1
fi

trap  "rm -f ${trap_list} 2>/dev/null" 0 1 2 15

[ "${do_backup}" ] && cp $1 ${out_dir}/,${out_tbl} 2>/dev/null

trap_list="${trap_list} ${tmp_file}"
trap  "rm -f ${trap_list} 2>/dev/null" 0 1 2 15

cat > ${tmp_file}

# Do not overwrite the table stright away, as we may be using
# it as an input to the pipeline. Furthermore, the input stream may
# be empty.

if [ -s ${tmp_file} ]
then
	# Use 'cp', as we may be operating across file systems.
	cp ${tmp_file} ${out_dir}/${out_tbl} 
	[ "${no_stdout}" ] || cat ${out_dir}/${out_tbl}
fi

exit 0

