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

RCS_ID='$Id: nsq-updseq,v 1.1 1998/05/29 20:35:06 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., 59 Temple Place Suite 330, Boston, MA 02111-1307
USA.
			----------------------

_EOH_
			exit 0
			;;
		-c*) new_seq=1 ; shift ;;
		-p*) posix_date=1 ; shift ;;
		*) break ;;
	esac
done

if [ "${posix_date}" ]
then
  time_stamp="$(date +%Y%m%d%H%M%S)"
else
  time_stamp="$(date +%s)"
fi

awk 'BEGIN { FS="\t"; OFS=FS; header = 0 ; comments = 0 ; j = 2 }

  header < 2 {
    if ( $1 ~ /^ *#/ ) { print ; comments++ ; next }
    else {
	  if ( '"${new_seq:=0}"' ) { 
		j = 1
		if ( header == 0 ) print "SEQ", $0
		else if ( '"${posix_date:=0}"' )
		  print "32 Unique record Sequence No.", $0
		else print "16 Unique record Sequence No.", $0
	  }
	  else print
	  header++
	}
	if ( header == 2 )  next
  }

  header >= 2 {
    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
  }'

