#!/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: dbstat [-H host] -d dbname\
\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"

while getopts "H:d:h" options; do
  case $options in
    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 * from pg_stat_database where datname = '$DATABASE'"

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

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

exit $RETURN

=head1 NAME

dbstat - Returns database statistics

=head1 SYNOPSIS

dbstat [-H hostname] -d name

=head1 OPTIONS

=over

=item -H hostname

connect to database server B<hostname>

=item -d name

print stats of database B<name>

=back

=head1 ENVIRONMENT

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

=head1 AUTHOR

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

=cut
