#!/bin/sh

############################################################################
#
# MODULE:       db.dropcolumn
# AUTHOR(S):   	Markus Neteler
# PURPOSE:      interface to db.execute to drop a column from an 
#               attribute table
#               - with special trick for SQLite
# COPYRIGHT:    (C) 2007 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: Drops a column from selected attribute table
#%  keywords: database, attribute table
#%End

#%flag
#%  key: f
#%  description: Force removal (required for actual deletion of files)
#%end

#%option
#% key: table
#% type: string
#% key_desc : name
#% description: Table from which to drop attribute column
#% required : yes
#% gisprompt: old_dbtable,dbtable,dbtable
#%end

#%option
#% key: column
#% type: string
#% description: Name of the column
#% required : yes
#% gisprompt: old_dbcolumn,dbcolumn,dbcolumn
#%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"`

#### check if we have awk
if [ ! -x "`which awk`" ] ; then
    g.message -e "awk required, please install awk or gawk first"
    exit 1
fi

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

#### setup temporary file
TEMPFILE="`g.tempfile pid=$$`"
if [ $? -ne 0 ] || [ -z "$TEMPFILE" ] ; then
    g.message -e "Unable to create temporary files" 
    exit 1
fi

cleanup()
{
 \rm -f "$TEMPFILE" "$TEMPFILE.coltypes" "$TEMPFILE.colnames" "$TEMPFILE.coldesc"
}

# what to do in case of user break:
exitprocedure()
{
   g.message -e 'User break!'
   cleanup
   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?}

table="$GIS_OPT_TABLE"

# check if DB parameters are set, and if not set them.
db.connect -c

database=`db.connect -p | grep '^database' | cut -d ':' -f2`
driver=`db.connect -p | grep '^driver' | cut -d ':' -f2`
# schema needed for PG?
col="$GIS_OPT_COLUMN"

force=$GIS_FLAG_F
if [ $force -eq 1 ] ; then
   g.message "Forcing ..."
fi


if [ "$col" = "cat" ] ; then
   g.message -w "Deleting <$col> column which may be needed to keep table\
      connected to a vector map"
   #cleanup
   #exit 1
fi

db.describe -c $GIS_OPT_TABLE | grep '^Column ' | cut -d':' -f2 | grep "^ ${col}" 2>&1 >/dev/null
if [ $? -ne 0 ] ; then
	g.message -e "Column <$col> not found in table"
	cleanup
	exit 1
fi

if [ $force -eq 0 ] ; then
    g.message "The <$col> column would be deleted."
    g.message message=""
    g.message "You must use the force flag to actually remove it. Exiting."
    exit 0
fi


if [ "$driver" = "sqlite" ] ; then
	#echo "Using special trick for SQLite"
	# http://www.sqlite.org/faq.html#q13
	db.describe -c $table | grep '^Column ' | cut -d':' -f2,3 | grep -v "${col}:" > "$TEMPFILE.coldesc"
	cat "$TEMPFILE.coldesc" | cut -d':' -f2 > "$TEMPFILE.coltypes"
	cat "$TEMPFILE.coldesc" | cut -d':' -f1 > "$TEMPFILE.colnames"
	COLDEF=`paste -d' ' "$TEMPFILE.colnames" "$TEMPFILE.coltypes" | tr '\n' ',' | sed 's+,$++g'`
	COLNAMES=`cat "$TEMPFILE.colnames" | tr '\n' ',' | sed 's+,$++g'`
echo "BEGIN TRANSACTION;
CREATE TEMPORARY TABLE ${table}_backup(${COLDEF});
INSERT INTO ${table}_backup SELECT ${COLNAMES} FROM ${table};
DROP TABLE ${table};
CREATE TABLE ${table}(${COLDEF});
INSERT INTO ${table} SELECT ${COLNAMES} FROM ${table}_backup;
DROP TABLE ${table}_backup;
COMMIT;" > "$TEMPFILE"
	db.execute input="$TEMPFILE"
	if [ $? -eq 1 ] ; then
	    	g.message -e "Cannot continue (problem deleting column)."
	    	cleanup
	    	exit 1
	fi
else
	echo "ALTER TABLE $table DROP COLUMN $col" | db.execute database="${database}" driver=${driver}
	if [ $? -eq 1 ] ; then
	    	g.message -e "Cannot continue (problem deleting column)."
	    	cleanup
	    	exit 1
	fi
fi

# cleanup
cleanup

exit 0

