#!/usr/bin/perl

use strict;
use warnings;

use RoPkg::Simba;
use English qw( -no_match_vars );
use Pod::Usage;
use Getopt::Long;

my %opt = ();
Getopt::Long::GetOptions(
    \%opt, qw[
             config|c=s
             callbacks|p
             help|h
           ]
);

my $simba;

sub main {
  if ($opt{help}) {
    pod2usage( -exitval => 0, -verbose => 2 );
    return;
  }

  if ($opt{config}) {
    $simba = new RoPkg::Simba(cfgFile => $opt{config});
  }
  else {
    $simba = new RoPkg::Simba(cfgFile => '/etc/simba/simba.cfg');
  }

  if ($opt{callbacks}) {
    $simba->RunCallbacks('userRequest');
    return;
  }

  foreach(@ARGV) {
      my $mirror_name = $_;
      
      eval {
        my $err_code = $simba->Run({ Name => $mirror_name });

        if ($err_code == 0) {
          ;
        }
        elsif ($err_code == 1) {
          print 'No such mirror in database',$RS;
        }
        elsif ($err_code == 2) {
          print 'Command for this mirror could not found in database',$RS;
        }
        else {
          print 'Something bad happend. Please check the log file (',$err_code,q{)},$RS;
          print Dumper($EVAL_ERROR),Dumper($ERRNO);
        }
      };

      if ( Exception::Class->caught('Mirror::InProgress') ) {
        print 'Sorry. Mirror ',$mirror_name,' is in progress',$RS;
        next;
      }
      elsif ( Exception::Class->caught('Mirror::Active') ) {
        print 'Sorry. Mirror is not active',$RS;
        next;
      }
      else {
        if (ref($EVAL_ERROR)) {
          print $EVAL_ERROR->trace(),$RS;
          next;
        }
        else {
          if ( $EVAL_ERROR ) {
            die $EVAL_ERROR;
          }
        }
      }
  }
}


main();
