#!/usr/bin/perl
#
# Copyright 1999 -- 2001, onShore Development Inc. <URL:http://www.onshore-devel.com/>
#
#
# This program is free software under the terms of the GNU General Public
# License (GPL). A copy of the GPL, "COPYING", should have been made
# available with this software.  If not, a copy may be obtained at 
# http://www.fsf.org/copyleft/gpl.html
#
# $Id: timesheet-dump,v 1.8 2001/08/29 22:23:15 adam Exp $
#

=head1 NAME

timesheet-dump - dump onShore TimeSheet data from database to disk

=cut

require '../etc/timesheet.conf';
use Getopt::Long;

my $backupdir = $Conf::BACKUPDIR;
my @dump_prog = ('pg_dump', '-d', '-D');
my @address = ();
my ($host, $port) = split(':', $Conf::DBADDR);
if ( length($host) > 0 ) {
    push @address, "-h", $host;
}
if ( length($port) > 0 ) {
    push @address, "-p", $port;
}
push @address, $Conf::SQLDB;

=head1 SYNOPSIS

B<timesheet-dump> [ C<-d> I<directory> ] [ C<-f> ] [ C<-a> ]

=head1 DESCRIPTION

B<timesheet-dump> extracts data from the onShore TimeSheet database
instance and dumps it onto disk.  This is primarily useful for backing
up data.  The program can be run on a nightly basis.

The data is dumped onto disk using one file per table.

=head1 OPTIONS

=over 4

=item C<-d> I<directory>

Specify the output directory for the dumped tables.  By default, the
C<BACKUPDIR> setting from the global configuration file is used.

=item C<-f>

Force an overwrite of existing files.

=item C<-a>

Only dump the data; do not include the data schema.

=back

=cut

# switch handling
if ( ! GetOptions( "d=s" => \$backupdir,
		   "f" => \$force_ovw,
		   "a" => \&no_schema  ) ) {
    die("Usage:\n  $0 [ -d directory ] [ -f ] [ -a ]\n");
}

sub no_schema {
    push(@dump_prog, "-a");
}

# sanity
if ( ! -d $backupdir ) {
    die "$0: data storage dir '$backupdir' does not exist\n";
}
if ( ! -w $backupdir ) {
    die "$0: data storage dir '$backupdir' is not writable\n";
}

my $table;
my @args;

for $table ($Conf::USER_DB, $Conf::CLIENT_DB, $Conf::JOB_DB, $Conf::HOURS_DB) {
    if ( -f "$backupdir/$table" ) {
	if ( $force_ovw ) {
	    warn "$0: file $backupdir/$table exists, overwriting\n";
	} else {
	    die "$0: file $backupdir/$table exists, won't overwrite unless -f\n";
	}
    }
    @args = (@dump_prog, "-t", $table, "-f", "$backupdir/$table",
	     @address);
    system(@args) == 0 or
	die "$0: @args failed: $?\n";
}

exit(0);

__END__

=head1 CONFIGURATION FILES

B<timesheet-dump> reads options from F<'../etc/timesheet.conf'>.
Options read include the PostgreSQL connect string, table names,
default backup directory, etc.

=head1 SEE ALSO

B<timesheet-load>(8)

=head1 AUTHOR

Craig Brozefsky, Adam Di Carlo, for onShore, Inc.

=cut
