#!/bin/sh

 # Copyright (c) 2008 Pierre-Emmanuel Andre <pea@raveland.org>
 # All rights reserved.
 #
 # Redistribution and use in source and binary forms, with or without
 # modification, are permitted provided that the following conditions
 # are met:
 #
 # 1. Redistributions of source code must retain the above copyright
 #    notice, this list of conditions and the following disclaimer.
 # 2. The name of the author may not be used to endorse or promote products
 #    derived from this software without specific prior written permission.
 #
 # THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 # AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 # THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 # EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 #

usage="usage: dbsize [-v] [-H host] -d dbname\
\n-v show sizes of user tables\
\n-H specifies the hostname of the machine on wich the server is running\
\n-d specifies the database name name (default template1)"

HOST=""
DATABASE="template1"
VERBOSE=""

while getopts "H:d:hv" options; do
  case $options in
    v ) VERBOSE=1 ;;
    H ) HOST="-h $OPTARG";;
    d ) DATABASE=$OPTARG;;
    h ) echo -e $usage
         exit 1;;
    \? ) echo -e $usage
         exit 1;;
    * ) echo -e $usage
          exit 1;;
  esac
done

Q="select pg_size_pretty(pg_database_size('$DATABASE')) as ${DATABASE}_size"

psql $HOST -d $DATABASE -c "$Q"
RETURN=$?

if [ $RETURN -ne 0 ]
then
    echo "\nTry $(basename $0) -h to see help"
fi

if [ "$VERBOSE" ] ; then
    Q="select schemaname as schema, relname as table, pg_size_pretty(pg_total_relation_size(relid)) as size from pg_stat_user_tables order by schemaname, relname"
    psql $HOST -d $DATABASE -c "$Q"
    RETURN=$?
fi

exit $RETURN

=head1 NAME

dbsize - Returns database size

=head1 SYNOPSIS

dbsize [-v] [-H hostname] -d name

=head1 OPTIONS

=over

=item -v

show sizes of user tables including indexes and sequences

=item -H hostname

connect to database server B<hostname>

=item -d name

print size of database B<name>

=back

=head1 ENVIRONMENT

B<PGDATABASE>, B<PGHOST>, B<PGPORT>, B<PGUSER> as described in psql(1).

=head1 AUTHOR

the "dbsize" program: Pierre-Emmanuel Andre < pea at raveland.org>

=cut
