#!/bin/sh
#
# Update record sequence values of an rdbtable.
#
# Author: Carlo Strozzi <carlos@linux.it>

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

my_name=$(basename $0)

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

    	NoSQL operator: ${my_name}

Usage:  ${my_name}  [options]  < input_table

Options:
    -c	Create new sequence column.
    -h	Print this help info.
    -p	Use Posix compliant date value in sequence fields.
    	Default is to use the non-portable GNU '+%s' format.

Updates the sequence column of an rdbtable. It is assumed that the
sequence column be the first (leftmost) in the table. If that is
not the case, then either the table must be pre-processed to meet
this requirement or the '-c' option has to be specified.

The unique sequence identifier is a string of the form :

    x_y

where :

    x = output of command 'date +%s' (GNU) or
        'date +%Y%m%d%H%M%S' (Posix)

    y = row No. within table

for a total length of up to 16 (GNU) or 32 (POSIX) characters.


This operator reads a NoSQL table via STDIN and produces the updated
table on STDOUT.

$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
			;;
		-c*) new_seq=1 ; shift ;;
		-p*) posix_date=1 ; shift ;;
		*) break ;;
	esac
done

${NSQAWK:-awk} -F"\t" -v posix_date=${posix_date} \
  -v new_seq=${new_seq} '
  BEGIN { header = 0 ; comments = 0 ; j = 2 }

  header < 2 {
    if ( $1 ~ /^ *#/ ) { print ; comments++ ; next }
    else {
	  if ( new_seq == 1 ) { 
		j = 1
		if ( header == 0 ) print "seq\t" $0
		else if ( posix_date == 1 ) print "32\t" $0
		else print "16\t" $0
	  }
	  else print
	  header++
	}
	if ( header == 2 )  next
  }

  header >= 2 {
	if( posix_date == 1 ) "date +%Y%m%d%H%M%S" | getline time_stamp
	else "date +%s" | getline time_stamp
    row_num = NR - comments - 2
	out_row = time_stamp "_" row_num
    for ( i = j; i <= NF; i++ )  out_row = out_row "\t" $i
	print out_row
  }'

