#!/usr/bin/perl -w
# $Id: bkp-remote.in.in,v 1.10 2004/03/01 18:03:22 x99laine Exp $
# Copyright (c) 2003 Jeremy Lain

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

use Getopt::Std;
use Bkp;

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

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


### functions ###

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

### main ###

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

  # process options
  if ($opts{'d'}) {
    Bkp::dprint("Running in debug mode ...\n");
    $Bkp::debug = 1;
  }
  
  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 remote {
  my $remote = shift;
  my $remotedir = "$conf{'savedir'}/$remote";
  my %robj = %{$conf{'remotes'}{$remote}};
 
  # checks
  if (Bkp::create_dir($remotedir,$opts{'n'})) {
    print("could not create '$remotedir', skipping remote '$remote'!\n");
    return;
  }
  
  if (Bkp::change_dir($remotedir,$opts{'n'})) {
    print("could not change to '$remotedir', skipping remote '$remote'!\n");
    return;
  }
  
  # build and execute command
  my $cmd = 'lftp -c "';
  $cmd .= "set net:max-retries ".$conf{'maxretries'}{'remotes'}."; ";
  $cmd .= "open $robj{'url'}";
  foreach my $section (@{$robj{'sections'}}) {
    $cmd .= " && mirror -c -e $section"; 
  }
  $cmd .= '"';
 
  Bkp::dprint("running : $cmd\n");
  if (!$opts{'n'}) {
    system($cmd) and
      print("error retrieving backups from '$remote'!\n");
  }
}

sub main {
  &init;

  foreach my $remote (@{$conf{'all'}{'remotes'}}) {
    if ( ($opts{'a'}) or 
         ($opts{'c'} and ($conf{'remotes'}{$remote}{'class'} =~ $opts{'c'})) or
	 ($opts{'o'} and ($remote =~ $opts{'o'})) ) {
      Bkp::dprint("\n* Processing remote $remote *\n");
      &remote($remote);
    }
  }
}


&main;
