#!/bin/sh

############################################################################
#
# MODULE:       db.in.ogr
# AUTHOR(S):   	Markus Neteler
# PURPOSE:      imports attribute tables in various formats
# COPYRIGHT:    (C) 2007, 2008 by Markus Neteler and the GRASS Development Team
#
#               This program is free software under the GNU General Public
#               License (>=v2). Read the file COPYING that comes with GRASS
#               for details.
#
#############################################################################

#%Module
#%  description: Imports attribute tables in various formats.
#%  keywords: database, attribute table
#%End

#%option
#% key: dsn
#% type: string
#% key_desc : name
#% gisprompt: old_file,file,input
#% description: Table file to be imported or DB connection string
#% required : yes
#%end

#%option
#% key: db_table
#% type: string
#% key_desc : name
#% description: Table name of SQL DB table
#% required : no
#%end

#%option
#% key: output
#% type: string
#% description: Name for output table
#% required : no
#%end

#%option
#% key: key
#% type: string
#% description: Name for auto-generated unique key column
#% required : no
#%end


if  [ -z "$GISBASE" ] ; then
    echo "You must be in GRASS GIS to run this program." >&2
 exit 1
fi

if [ "$1" != "@ARGS_PARSED@" ] ; then
  exec g.parser "$0" "$@"
fi

PROG=`basename "$0"`

# setting environment, so that awk works properly in all languages
unset LC_ALL
LC_NUMERIC=C
export LC_NUMERIC


# what to do in case of user break:
exitprocedure()
{
 g.message -e 'User break!'
 exit 1
}
# shell check for user break (signal list: trap -l)
trap "exitprocedure" 2 3 15

### setup enviro vars ###
eval `g.gisenv`
: ${GISBASE?} ${GISDBASE?} ${LOCATION_NAME?} ${MAPSET?}

# check if we want to connect to real DB
if [ ! -z "$GIS_OPT_DB_TABLE" ] ; then
  INPUT="$GIS_OPT_DB_TABLE"
else
  INPUT="$GIS_OPT_DSN"
fi

if [ -z "$GIS_OPT_OUTPUT" ] ; then
  # file name laundery
  TMPNAME=`echo "$INPUT" | tr -s '.' '_'`
  GIS_OPT_OUTPUT=`basename "$TMPNAME"`
fi

if [ -z "$GRASS_OVERWRITE" ] ; then
  if [ `db.tables -p | grep "^${GIS_OPT_OUTPUT}$"` ] ; then
     g.message -e "Table <${GIS_OPT_OUTPUT}> already exists"
     exit 1
  fi
else
  # user gave --o
  db.droptable -f --q "$GIS_OPT_OUTPUT" >/dev/null 2>/dev/null
fi

# treat DB as real vector map...
if [ ! -z "$GIS_OPT_DB_TABLE" ] ; then
  LAYER="layer=$GIS_OPT_DB_TABLE"
fi

# check ERRORs and cat and cat_ issues (maybe problem with translated messages)
# we import faking a map which generates only the attribute table:
### check-me: is the quoting ok?
WARNING="`v.in.ogr --q dsn=\"$GIS_OPT_DSN\" $LAYER out=$GIS_OPT_OUTPUT -o --o 2>&1 | grep -i 'ERROR\|cat' | grep -v 'truncated'`"
if [ -n "$WARNING" ] ; then
   echo "$WARNING"
   if [ -n "$GIS_OPT_DB_TABLE" ] ; then
      g.message -e "Input DSN <$INPUT> not found or not readable"
   else
      g.message -e "Input table <$INPUT> not found or not readable"
   fi
   exit 1
fi

# rename "key"  col if requested from "cat" (generated by v.in.ogr) to new name:
if [ -n "$GIS_OPT_KEY" ] ; then
   echo "ALTER TABLE $GIS_OPT_OUTPUT ADD COLUMN $GIS_OPT_KEY integer" | db.execute
   echo "UPDATE $GIS_OPT_OUTPUT SET $GIS_OPT_KEY=cat" | db.execute
fi

# ... and immediately drop the empty geometry
eval `g.findfile element=vector file="$GIS_OPT_OUTPUT" mapset="$MAPSET"`
if [ ! "$file" ] ; then
   g.message -e "Something went wrong. Should not happen"
   exit 1
else
   # remove the vector part
   rm -rf "$file"
fi

# get rid of superfluous auto-added cat column (and cat_ if present)
db.dropcol --q -f "$GIS_OPT_OUTPUT" colum=cat >/dev/null 2>/dev/null
if [ ! -z "$WARNING" ] ; then
   db.dropcol --q -f "$GIS_OPT_OUTPUT" colum=cat_ >/dev/null 2>/dev/null
fi

RECORDS=`db.describe -c "$GIS_OPT_OUTPUT" | grep '^nrows' | sed 's+ ++g' | cut -d':' -f2`
g.message "Imported table <$GIS_OPT_OUTPUT> with $RECORDS rows"

exit 0
