#!/bin/sh
#
# Converts an rdbtable to shell variable assignments.
#

RCS_ID='$Id$'

my_name=$(basename $0)

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

        NoSQL operator: ${my_name}

Usage:  ${my_name}  [options]  [rdbtable]

Options:
    -h    Print this help info.
    -p P  Prefix each output variable (column) name with string 'P'.

Converts an rdbtable to shell variable format (VARIABLE=value), handy
for grabbing a record into a shell program. If the rdbtable contains
more than one row of data, then the assignments will be those of the
last row. Any single-quotes in the 'value' part of the assignment are
escaped with the ASCII sequence '&#39;', not to cause troubles to the
invoking shell.

This operator reads an rdbtable from a file and prints the requested info
to STDOUT. If no rdbtable is specified on the command line, then the input
table is read from STDIN.

An example of usage of this operator from within a shell script is :

                 eval \`${my_name} [rdbtable]\`
or :
                 eval \`${my_name} < rdbtable\`

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

case ${1} in
  -*)
    echo "Usage: ${my_name} [options] [rdbtable]" >&2
    exit 1
    ;;
esac

awk 'BEGIN { NULL=""; FS="\t"; OFS=FS;}
# Table comments.
r==0 && $0 ~ /^ *#/ { next }
# Column names.
r==0 { split($0, c_names); r++; next; }
# Column definitions.
r == 1 { hdr_nr=NR; r++; next; }
END {
  if( hdr_nr != NR )
    while( c_names[++c] != NULL ) {
	  # Any single quotes MUST be escaped in data.
	  gsub( "'"'"'", "\&#39;", $c )
	  print "'"${prefix}"'" c_names[c] "='"'"'" $c "'"'"'"
	}
  else
	while( c_names[++c] != NULL )
	  print "'"${prefix}"'" c_names[c] "='"'"'" NULL "'"'"'"
}' ${1}

exit $?

