#!/bin/ash
# *********************************************************************
# ctime: take a column containing the No. of seconds since epoch and
# turn it into local time values.
#
# 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: ctime,v 1.6 2006/03/10 11:26:13 carlo Exp $

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

while :
do
   case $1 in
	-N|--no-header)		no_hdr="$1" ;;
	-i|--input)		shift; i_file="$1" ;;
	-o|--output)		shift; o_file="$1" ;;
	-F|--format)		shift; o_fmt="$1" ;;
	-h|--help)
	     grep -v '^#' $NOSQL_INSTALL/help/ctime.txt
	     exit 1
	;;
	--show-copying)
	     cat $NOSQL_INSTALL/doc/COPYING
	     exit 1
	;;
	--show-warranty)
	     cat $NOSQL_INSTALL/doc/WARRANTY
	     exit 1
	;;
	-*) ;;				# Skip unknown options.
	*) break ;;
   esac
   shift
done

if [ $# -ne 1 ]
then
   echo Usage: ctime [options] column >&2
   exit 1
fi

: ${TMPDIR:=/tmp} ${o_fmt:="%a %b %d %H:%M:%S %Z %Y"}

tmp_a=`mktemp $TMPDIR/ctime.XXXXXX` || exit $?
tmp_b=`mktemp $TMPDIR/ctime.XXXXXX` || exit $?

# Set-up trapping on signals.
trap "rm -f $tmp_a $tmp_b" 0
trap "exit 2" 1 2 3 15

cat ${i_file:--} > $tmp_a || exit $?

project "$1" --input $tmp_a |
	compute "$1 = \"1970-01-01 UTC + \" $1 \"sec\"" |
	filter $no_hdr -- date -f - "+$o_fmt" > $tmp_b || exit $?

if [ "$o_file" = "" ]
then
   notcolumn $no_hdr "$1" --input $tmp_a | paste - $tmp_b
else
   notcolumn $no_hdr "$1" --input $tmp_a |
	paste - $tmp_b > $o_file || exit $?
fi

# End of program.
