#!/bin/ash
# *********************************************************************
# sqlitetotable: Builds a valid NoSQL table from a SQLite database table
#
# Copyright (c) 2006,2007,2009 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.
#
# *********************************************************************

# Get local settings and apply defaults.
: ${TMPDIR:=/tmp} ${NOSQL_CHARSET:=utf-8}
: ${NOSQL_INSTALL:=@NOSQL_INSTALL@}
: ${SWU_INSTALL:=@SWU_INSTALL@}
: ${PATH:=@LOCAL_PATH@}

export NOSQL_INSTALL SWU_INSTALL PATH TMPDIR NOSQL_CHARSET

tab="	"                       # Warning: this must be a physical TAB!
i_file=
o_file=
name=
cmd=
v=				# SQLite version indicator.

while [ $# -gt 0 ]
do
   case $1 in
        -i|--input)     shift;  i_file="$1" ;;
        -o|--output)    shift;  o_file="$1" ;;
        -3)    		v=3 ;;

        -h|--help)
                grep -v '^#' $NOSQL_INSTALL/help/sqlitetotable.txt
                exit 0
        ;;
        --show-copying)
             cat $NOSQL_INSTALL/doc/COPYING
             exit 1
        ;;
        --show-warranty)
             cat $NOSQL_INSTALL/doc/WARRANTY
             exit 1
        ;;
        -*) ;;                          # Skip unknown options.
        *) 
         if [ "$name" != "" ] 
         then
              cmd="$1"                  # SQL select command.
         else
              name="$1"                 # Database name.
        fi 
        ;;
   esac
   shift
done

[ "$o_file" = "" ] || exec > "$o_file"

{
if [ "$i_file" != "" ]
then
  sqlite$v -init "$i_file" "$name" .quit
else
  sqlite$v -separator "$tab" -header "$name" "$cmd"
fi
}|
  _awk -F '\t' -- 'NR==1{
        gsub(/[^a-zA-Z0-9_\t]/,"_")
        sub(/^/,"\001");gsub(/\t/,"\t\001")
        print
  }
  NR > 1 {
        for (i=1;i<=NF;i++) {
            sub(/^ +/,"",$i); sub(/ +$/,"",$i)
            if (i>1) printf("\t")
            printf("%s",$i)
        }
        print ""
  }'

exit $?

# EOF
