#!/bin/bash
#
# This script dumps your Bacula catalog in ASCII format
# It works for MySQL, SQLite, and PostgreSQL
#
#  $1 is the name of the database to be backed up and the name
#     of the output file (default = bacula).
#  $2 is the user name with which to access the database
#     (default = bacula).
#  $3 is the password with which to access the database or "" if no password
#     (default ""). WARNING!!! Passing the password via the command line is 
#     insecure and should not be used since any user can display the command 
#     line arguments and the environment using ps.  Please consult your
#     MySQL or PostgreSQL manual for secure methods of specifying the
#     password.
#  $4 is the host on which the database is located
#     (default "")
#
#

. /etc/sysconfig/bacula

. shell-var
. shell-quote

__section_range()
{
    local section
    quote_sed_regexp_variable section "$1"
    echo "/^[[:space:]]*$section[[:space:]]*{[[:space:]]*\(#.*\)\?\$/,/^[[:space:]]*}[[:space:]]*\$/"
}

get_param()
{
    local file="$1";shift
    local section="$1";shift
    local name="$1";shift

    local qname
    quote_sed_regexp_variable qname "$name"
    cat "$file" | sed -e "s/;/\n/g"| sed -n  -e "$(__section_range "$section") s/^[[:space:]]*$qname[[:space:]]*=[[:space:]]*\"\?\([^\"]\+\)\"\?[[:space:]]*$/\1/p"
}

RETVAL=0
DB_NAME=`get_param /etc/bacula/bacula-dir.conf Catalog dbname`
DB_USER=`get_param /etc/bacula/bacula-dir.conf Catalog user`
DB_PWD=`get_param /etc/bacula/bacula-dir.conf Catalog password`
DB_HOST=`get_param /etc/bacula/bacula-dir.conf Catalog DBAddress`
BINDIR=/usr/bin

[[ -n $1 ]] && DB_NAME="$1"
[[ -n $2 ]] && DB_USER="$2"
[[ -n $3 ]] && DB_PWD="$3"
[[ -n $4 ]] && DB_HOST="$4"
[[ -z "$DB_HOST" ]] && DB_HOST="localhost"

cd /var/lib/bacula
rm -f $DB_NAME.sql

case "$BACULA_BACKEND" in
    postgresql)
        $BINDIR/pg_dump -U "$DB_USER" -h "$DB_HOST" "$DB_NAME" > "$DB_NAME.sql"
        ;;
    sqlite3)
        echo ".dump" | $BINDIR/sqlite3 "$DB_NAME.db" > "$DB_NAME.sql"
        ;;
    mysql)
        $BINDIR/mysqldump -h "$DB_HOST" -u "$DB_USER" --password="$DB_PWD" -f --opt "$DB_NAME" > "$DB_NAME.sql"
        ;;
    *)
        echo "Unknown database type"
        RETVAL=1
        ;;
esac

exit "$RETVAL"

