#!/usr/bin/perl -w
# Copyright (c) 2003-2006 Jeremy Lain
# Copyright (c) 2005-2006 Sylvain Joyeux

use strict;
use lib '/usr/share/bkp';

use Getopt::Std;
use Date::Format;
use Sys::Hostname;
use Bkp;

# package 
my $package = "bkp-svn";

# config and options
my (%conf,%opts);


sub syntax {
   print "[ This is $package (bkp 0.6.1), a subversion backup utility ]\n\n",
        "Syntax:\n",
        "  $package <action> [options]\n\n",
        " Actions:\n",
        "  -a           - process all repositories\n",
	"  -c <class>   - process repositories of class <class>\n",
        "  -h           - this help message\n",
	"  -o <repo>    - process only repository <repo>\n\n",
        " Options:\n",
        "  -d           - debug mode\n",
        "  -f <file>    - use <file> as config file\n",
        "  -n           - simulation mode (do not touch filesystem)\n";
}


sub init {
  if ( not getopts('dhnf:ac:o:', \%opts) or $opts{'h'}) {
    &syntax();
    exit(1);
  }

  # process options
  if ($opts{'d'}) {
    $Bkp::debug = 1;
    Bkp::dprint("Running in debug mode ...\n");
  }
  
  if ($opts{'n'}) {
    Bkp::dprint("Running in simulation mode ...\n");
  }
  
  # check the requested action
  if (!$opts{'a'} and !$opts{'c'} and !$opts{'o'}) {
    print("no action was selected\n");
    &syntax;
    exit(1);
  }

  # read config file
  if ($opts{'f'}) {
    %conf = Bkp::read_conf($opts{'f'});
  } else {
    %conf = Bkp::read_conf($Bkp::confile);
  }
}


sub main {
  &init;

  my $date = time2str("%Y-%m-%d", time);
  my $hostname = hostname;
  my $svndir = "$conf{'savedir'}/$hostname/svn";
 
  # create directory
  if (Bkp::create_dir($svndir,$opts{'n'})) {
    print("could not create '$svndir', bailing out!");
    exit(1);
  }

  # do the backups
  foreach my $repository (@{$conf{'all'}{'svn'}}) {
    if ( ($opts{'a'}) or 
         ($opts{'c'} and ($conf{'svn'}{$repository}{'class'} eq $opts{'c'})) or
	 ($opts{'o'} and ($repository eq $opts{'o'})) ) {
      Bkp::dprint("\n* Processing repository $repository *\n");

      my $path = $conf{'svn'}{$repository}{'path'};
      my $ofile = "$svndir/$repository.$date";
      my $cmd = "svnadmin dump -q $path";
      ($ofile, $cmd) = Bkp::add_pipe_opts($ofile, $cmd, %conf);
      $cmd .= " > $ofile";

      Bkp::dprint("running : $cmd\n");
      if (!$opts{'n'}) {
        if (system($cmd)) {
          print("error dumping repository '$path'!\n");
        }
      }
      Bkp::dprint("\n");
    }

    # erase old backups
    Bkp::dprint("** Erasing old backups **\n");
    Bkp::expire_dir($svndir,$conf{'svn'}{$repository}{'maxdays'},$opts{'n'});
  }
}

&main();

