#!/bin/sh

############################################################################
#
# MODULE:       db.droptable
# AUTHOR(S):   	Markus Neteler
# PURPOSE:      interface to db.execute to drop an attribute table
# 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 an 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 to drop
#% required : yes
#% gisprompt: old_dbtable,dbtable,dbtable
#%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

# 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 ###
LOCATION_NAME=`g.gisenv get=LOCATION_NAME`
GISDBASE=`g.gisenv get=GISDBASE`

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

# check if table exists
db.describe -c "$GIS_OPT_TABLE" >/dev/null 2>/dev/null
if [ $? -ne 0 ] ; then
   g.message -e "Table <$table> not found in current mapset"
   exit 1
fi

# check if table is used somewhere (connected to vector map)
USEDINMAPS=`grep "$table" "$GISDBASE/$LOCATION_NAME"/*/vector/*/dbln | sed -e 's+/dbln:.*$++g' -e 's+^.*/++'`
if  [ -n "$USEDINMAPS" ] ; then
   g.message -w "Deleting <$table> table which is attached to following map(s):"
   for i in $USEDINMAPS ; do
       echo "`basename "$i"`"
   done
fi

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


echo "DROP TABLE $table" | db.execute database="$database" driver="$driver"
if [ $? -ne 0 ] ; then
    g.message -e "Cannot continue (problem deleting column)."
    exit 1
fi

exit
