#!/bin/sh
######################################################################
# html2pgsql.sh
######################################################################
PrintHelp()
{
cat <<EOF

html2pgsql.sh

Converts Microsoft Access "Export as HTML" table dump to an SQL
script that imports the data into the specified table in the
specified PostgreSQL database.

Uses html2tabbed.sh, which has some limits on capabilities.

Usage:
    html2pgsql.sh -h
    html2pgsql.sh [ options ] inputfile.html table

    Unless the -p option is specified, the script saves output as
    table.dump where table is the table name (arg 2). A commented
    header with instructions for loading the table precedes the SQL
    commands. To use:

    1. Be sure table exists in target database with appropriate
       columns and types.
    2. Execute table.dump as the SQL file it is:
       psql -d database -U databaseuser -f table.dump


Options:
    -h
        Display this help message.
    -p
	Pass-through; write the SQL script to standard output with no
	instruction header.

EOF
return  
}

WriteInstructions()
{
    cat <<EOF
/*********************************************************************

To load the "$Table" table:
psql -d database -U user -f $OutFile

*********************************************************************/

EOF
    return
}

WriteToStdOut()
{
    cat <<EOF
COPY "$Table" FROM stdin;
EOF
    $ScriptDir/html2tabbed.sh < $InFile
    echo "\."
    return
}

######################################################################
# Parse command line options
while getopts "hp" Option
do
    case $Option in
      h ) PrintHelp
          exit
          ;;
      p ) PassThru=True
          ;;
    esac
done

shift $(( $OPTIND - 1 ))

if [ $# -ne 2 ]
then
    echo Usage: html2pgsql.sh [ -hp ] inputfile.html table
    exit
fi
if echo $0 | grep '/' >/dev/null
then
    ScriptDir=`echo $0 | rev | cut -d '/' -f 2- | rev`
else
    ScriptDir=`pwd`
fi
InFile=$1
Table=$2
OutFile=$Table.dump

if [ $PassThru ]
then
    WriteToStdOut
else
    WriteInstructions > $OutFile
    WriteToStdOut >> $OutFile
fi
