#!/bin/sh
#
# Shell script to update PostgreSQL tables from Bacula version 6.2.x to 6.4.0
#
echo " "
echo "This script will update a Bacula PostgreSQL database from version 1014 to 1015"
echo "	which is needed to convert from Bacula version 6.2.x to 6.4.x"
echo " "

bindir=/usr/lib/postgresql/9.1/bin
PATH="$bindir:$PATH"
db_name=${db_name:-bacula}

DBVERSION=`psql -d ${db_name} -t --pset format=unaligned -c "select VersionId from Version" $*`
if [ $DBVERSION != 1014 ] ; then
   echo " "
   echo "The existing database is version $DBVERSION !!"
   echo "This script can only update an existing version 1014 database to version 1015."
   echo "Error. Cannot upgrade this database."
   echo " "
   exit 1
fi

if psql -f - -d ${db_name} $* <<END-OF-DATA

BEGIN;
ALTER TABLE Media ADD COLUMN volabytes bigint default 0;
ALTER TABLE Media ADD COLUMN volapadding bigint default 0;
ALTER TABLE Media ADD COLUMN volholebytes bigint default 0;
ALTER TABLE Media ADD COLUMN volholes integer default 0;

UPDATE Version SET VersionId=1015;
COMMIT;

END-OF-DATA
then
   echo "Update of Bacula PostgreSQL tables succeeded."
else
   echo "Update of Bacula PostgreSQL tables failed."
fi

psql -f - -d ${db_name} $* <<EOF
-- This part may fail, but it's not a big problem
set client_min_messages = fatal;
CREATE INDEX media_poolid_idx on Media (PoolId);
CREATE INDEX media_storageid_idx ON Media (StorageId);
set client_min_messages = default;
EOF


exit 0
