#!/usr/bin/perl
#version 4

use strict;


use vars qw($opt_P $opt_r $port_string $opt_q $opt_h $client $opt_b $opt_n @opt_U $opt_R $opt_a);

$client='/usr/bin/cleo-client';

GetOptsTillCan('P=i'=>\$opt_P,
               'q=s'=>\$opt_q,
               'r=' =>\$opt_r,
               'h=' =>\$opt_h,
               'b=i'=>\$opt_b,
               'n=i'=>\$opt_n,
               'U=+'=>\@opt_U,
               'R=s'=>\$opt_R,
               'a=s'=>\$opt_a
              );
# -r -> recursive     -b -> autoblock    -n -> autononblock
# -R -> reason        -a -> 'as user'
# if -b and no -U specified then all_block set\unset


die "Usage: cleo-blocktask [-q queue][-P port][-r][-U userlist][-R 'reason']\n".
    "                  [-a as_user] -b|-n [1/0]\n\n"
  if($opt_h);

$port_string  =" -p $opt_P" if $opt_P =~ /^\d+$/;
$port_string .=" -R" if $opt_r;
$port_string .=" -q $opt_q" if $opt_q;
$port_string .=" -O '$opt_R'" if $opt_R;
$port_string .=" -S $opt_a" if $opt_a;
$port_string .=" -L ".join(',',@opt_U) if(scalar(@opt_U));

if(defined $opt_b){
  if(@opt_U>0){
    if($opt_b){
      $b = '-a 1';
    }else{
      $b = '-a 0';
    }
  }
  else{
    if($opt_b){
      $b = '-a 5';
    }else{
      $b = '-a 4';
    }
  }
}
elsif(defined $opt_n){
  if($opt_n){
    $b = '-a 3';
  }else{
    $b = '-a 2';
  }
}
else{
  print "-b, -n or -x reqired!\n";
  exit 1;
}

exec("$client $port_string $b $ARGV[0]") or die("Internal error. Unable to run client application\n");





#
#  Gets opts like this: ('X=i', \$Xoption,...) (this means "option '-X 10' to variable $Xoption=10)
#  The scans command line for options till founds argument '--' or non-specified
#  option, or not '-' prefixed argument.
#  Specifications of options (what goes after 'X='):
#  i - integer
#  s - string
#  + - cumulative value (variable MUST be a list)
#  nothing - flag
#
sub GetOptsTillCan{

  my %args=@_;
  my ($k,$nk,$nv,$a,$next,%types);

  foreach $k (keys(%args)){
    $k =~ /^(\S+)(\=)(.*)/ or next;
    $nk=$1;
    $nv=$args{$k};
    $types{$nk} = $3;

    delete $args{$k};
    $args{$nk} = $nv;
  }

  while($next=shift @ARGV){
    last if(substr($next,0,1) ne '-');
    last if($next eq '--');
    $a=substr($next,1);
    undef $next;
    last unless(exists $args{$a});
    if(($types{$a} eq 'i') || ($types{$a} eq 's')){
      $a=$args{$a};
      $$a=shift @ARGV;
    }
    elsif($types{$a} eq ''){
      $a=$args{$a};
      $$a=1;
    }elsif($types{$a} eq '+'){
      $a=$args{$a};
      push @$a, shift @ARGV;
    }
  }
  unshift @ARGV, $next if(defined $next);
}

