#!/bin/sh
#-------------------------------------------------------------------------
#
# vacuumdb--
#    vacuum a postgres database
#
#    This script runs psql with the "-c" option to vacuum
#    the requested database.
#
# Copyright (c) 1994, Regents of the University of California
#
#
# IDENTIFICATION
#    $Header: /cvsroot/pgsql/src/bin/scripts/Attic/vacuumdb,v 1.3 1999/12/07 22:41:44 momjian Exp $
#
#-------------------------------------------------------------------------

CMDNAME=`basename $0`

PSQLOPT=
verbose=
analyze=
table=
dbname=

while [ $# -gt 0 ]
do
    case "$1" in
	--help|-\?)
		usage=t
		break
		;;
# options passed on to psql
	--host|-h)
		PSQLOPT="$PSQLOPT -h $2"
		shift;;
        -h*)
                PSQLOPT="$PSQLOPT $1"
                ;;
        --host=*)
                PSQLOPT="$PSQLOPT -h "`echo $1 | sed 's/^--host=//'`
                ;;
	--port|-p)
		PSQLOPT="$PSQLOPT -p $2"
		shift;;
        -p*)
                PSQLOPT="$PSQLOPT $1"
                ;;
        --port=*)
                PSQLOPT="$PSQLOPT -p "`echo $1 | sed 's/^--port=//'`
                ;;
	--user|--username|-U)
		PSQLOPT="$PSQLOPT -U '$2'"
		shift;;
        -U*)
                PSQLOPT="$PSQLOPT $1"
                ;;
        --user=*)
                PSQLOPT="$PSQLOPT -U "`echo $1 | sed 's/^--user=//'`
                ;;
        --username=*)
                PSQLOPT="$PSQLOPT -U "`echo $1 | sed 's/^--username=//'`
                ;;
	--password|-W)
		PSQLOPT="$PSQLOPT -W"
		;;
	--echo|-e)
		PSQLOPT="$PSQLOPT -e"
		;;
	--quiet|-q)
		PSQLOPT="$PSQLOPT -o /dev/null"
		;;
	--dbname|--database|-d)
		dbname="$2"
		shift;;
        -d*)
                dbname=`echo $1 | sed 's/^-d//'`
                ;;
        --dbname=*)
                dbname=`echo $1 | sed 's/^--dbname=//'`
                ;;
        --database=*)
                dbname=`echo $1 | sed 's/^--database=//'`
                ;;
# options converted into SQL command
	--analyze|-z)
		analyze="ANALYZE "
		;;
	--table|-t)
		table="$2"
		shift;;
        -t*)
                table=`echo $1 | sed 's/^-t//'`
                ;;
        --table=*)
                table=`echo $1 | sed 's/^--table=//'`
                ;;
	--verbose|-v)
		verbose="VERBOSE "
		;;

	-*)
		echo "$CMDNAME: Unrecognized option: $1. Try -? for help."
		exit 1
		;;
	*)
		dbname="$1"
		;;
    esac
    shift
done


if [ "$usage" ]; then
	echo "Usage: $CMDNAME [-h server] [-p port] [-U username] [-d dbname] \\"
	echo "       [-z|--analyze] [-v|--verbose] [-t|--table 'table[(columns)]'] [dbname]"
	exit 0
fi

if [ -z "$dbname" ]; then
	echo "$CMDNAME: Missing required argument database name. Try -? for help."
	exit 1
fi

psql $PSQLOPT -d "$dbname" -c "VACUUM $verbose$analyze$table"

if [ $? -ne 0 ]; then
	echo "$CMDNAME: Vacuum failed."
	exit 1
fi

exit 0
