#! /usr/bin/perl -w
use strict;
use Getopt::Long qw/GetOptionsFromArray/;
use Pod::Usage;
use App::PgCryobit;


my @config_paths =  ('pg_cryobit.conf',
		     ( $ENV{HOME} // '.' ).'/pg_cryobit.conf',
		     '/etc/pg_cryobit.conf' );

my %OPTIONS_HASH;


my @OPTIONS_ARRAY = @ARGV;
my $COMMAND = shift @OPTIONS_ARRAY if ( @OPTIONS_ARRAY &&  ( $OPTIONS_ARRAY[0] !~ /--/ ) );

my $opts_result = 
  GetOptionsFromArray(
	     \@OPTIONS_ARRAY,
	     \%OPTIONS_HASH,
	     "conf=s",
	     "file=s",
	     "deepclean",
	    );

## Deal with help and exit
pod2usage(1) unless $COMMAND;
pod2usage(1) if $COMMAND eq 'help' ;
pod2usage(-exitstatus => 0, -verbose => 2) if $COMMAND eq 'man';


if ( $OPTIONS_HASH{conf} ){
  @config_paths = ( $OPTIONS_HASH{conf} );
}
my $app =  App::PgCryobit->new({ config_paths => \@config_paths });
# Store the given options in the application.
$app->options(\%OPTIONS_HASH);

## Check the app can perform the command
my $command_method = 'feature_'.$COMMAND;
pod2usage(1) unless $app->can($command_method);


## Always check the config. It might have change since last call.
my $conf_code = $app->feature_checkconfig();
exit($conf_code) if ( $conf_code );

my $command_code  = $app->$command_method();
exit($command_code);


__END__

=head1 NAME

pg_cryobit - Manage PostgreSQL continuous backup

=head1 SYNOPSIS

pg_cryobit help|man|checkconfig|archivewal|rotatewal|archivesnapshot|fullarchive [options]

=head1 OPTIONS

=head2 COMMANDS

=over 8

=item B<checkconfig>

Checks the configuration file is correct.

=item B<archivewal>

Archive a given WAL file using the configured shipper. Requires options --file.

=item B<rotatewal>

Forces a wal rotation. Checks the rotated file has been shipped. No required options.

=item B<archivesnapshot>

Take a snapshot archive of the whole database. No required options.

=item B<fullarchive>

rotatewal and archivesnapshot. Options apply.

=back

=head2 COMMANDS OPTIONS

=over 8

=item  --conf=<file>

Specify configuration file on the command line. Applies to all commands.

=item --file=<file>

Specify file to handle. Applies to archivewal

=item --deepclean

Remove anything earlier than the last archivesnapshot. Applies to archivesnapshot

=back

=head2 CONFIGURATION

If no --conf option is given, pg_cryobit looks for a pg_cryobit.conf file in the following directories:

 The current directory

 Your HOME directory (HOME is defined)

 Your system's /etc directory.

=head2 SEE ALSO

perldoc App::PgCryobit

=head2 COPYRIGHT AND LICENSE

Copyright 2010 by Jerome Eteve.

This is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

=cut
