#!/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
             analyze|a
           ]
);

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{analyze}) {
    return $simba->RunCallbacks('analyzeMirrors');
  }

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

  if ($simba->CheckDB != 0) {
    print 'Problems found in database. Aborting.',$RS;
    return;
  }

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

      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;
      }
      elsif ( my $e = Exception::Class->caught('DB::NoResults') ) {
        if ( $e->pkg_name eq 'RoPkg::Simba::Commands' ) {
          print 'Sorry. No command found in database for this mirror',$RS;
        }
        elsif ($e->pkg_name eq 'RoPkg::Simba::Mirrors') {
          print 'Sorry. No such mirror in database', $RS;
        }
        else {
          print 'Some other error occured.',$RS,Dumper($e),$RS;
        }
      }
      else {
        if (ref($EVAL_ERROR)) {
          print 'Exception throwed: ',ref($EVAL_ERROR),$RS,
                $EVAL_ERROR->error, $RS;
          next;
        }
        else {
          if ( $EVAL_ERROR ) {
            die $EVAL_ERROR;
          }
        }
      }
  }
}


main();
