package tvapp;

use strict;

require Exporter;
use vars       qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);

# set the version for version checking
$VERSION     = 0.00.3;

@ISA         = qw(Exporter);
@EXPORT      = qw(&cronaddcmd &cronlsserials &cronrmserial);
%EXPORT_TAGS = ( );     # eg: TAG => [ qw!name1 name2! ],

# your exported package globals go here,
# as well as any optionally exported functions
#@EXPORT_OK   = qw($Var1 %Hashit &func3);
@EXPORT_OK   = qw(&cronaddcmd &cronlsserials &cronrmserial);
#@EXPORT_OK   = qw($Var1 %Hashit &func3);

#use vars qw($Var1 %Hashit);
# non-exported package globals go here
#use vars qw(@more $stuff);

# initialize package globals, first exported ones
#$Var1   = '';
#%Hashit = ();

# then the others (which are still accessible as $Some::Module::stuff)
#$stuff  = '';
#@more   = ();


# file-private lexicals go here
#my $priv_var    = '';
#my %secret_hash = ();


sub cronaddcmd {
   #my $self      = shift;
   my $title     = $_[0];
   my $hh        = $_[1];
   my $mm        = $_[2];
   my $dow       = $_[3];
   my $cmd       = $_[4];

   use Config::Crontab;
   my $ct = new Config::Crontab;
   $ct->read || die "could not read crontab. $?\n";;

   cronclean(\$ct, $title);

   ## get blocks, remove unwanted comments
   for my $block ( $ct->blocks ) {
        $block->remove($block->select(
                          -type    => 'comment',
                          -data_re => '# DO NOT EDIT THIS FILE'
                                     )
                      );
        $block->remove($block->select(
                          -type    => 'comment',
                          -data_re => '# \(/tmp'
                                     )
                      );
        $block->remove($block->select(
                          -type    => 'comment',
                          -data_re => '# \(Cron version '
                                     )
                      );
   }

   my $comment = "# Record serial \"$title\"";

   ## make another block using Block methods
   my $block = new Config::Crontab::Block;
   $block->last( new Config::Crontab::Comment( -data    => $comment ));
   $block->last( new Config::Crontab::Event  ( -minute  => $mm ,
                                               -hour    => $hh ,
                                               -dow     => $dow ,
                                               -command => $cmd ) );

   ## add this block to crontab file
   $ct->last ($block);

   ## save the new crontab
   $ct->write || die "Konnte crontab nicht schreiben. $!\n";;
   exit 0;
}

sub cronclean {
   #my $self      = shift;
   my $ct        =  ${$_[0]};
   my $title     =  $_[1];
   $title        =~ s/\(/\\\(/g;
   $title        =~ s/\)/\\\)/g;

#    print "\n";
#    print "remove $title\n";
#    print "---------------------\n";

#    print "\n";
#    print "crontab before remove\n";
#    print "---------------------\n";
#    print $ct->dump;

   ## get blocks, remove unwanted comments and the command block
   for my $block ( $ct->blocks ) {
        $block->remove($block->select(
                          -type    => 'comment',
                          -data_re => '# DO NOT EDIT THIS FILE'
                                     )
                      );
        $block->remove($block->select(
                          -type    => 'comment',
                          -data_re => '# \(/tmp'
                                     )
                      );
        $block->remove($block->select(
                          -type    => 'comment',
                          -data_re => '# \(Cron version '
                                     )
                      );
        $block->remove($block->select( -type    => 'comment',
                                       -data_re => "\"$title\"" )
             ) ;
        # old format (kalva <= 0.7.0)
        $block->remove($block->select( -type    => 'event',
                                       -data_re => "\/$title" . "_\`/" )
             ) ;
        # new format (kalva >= 0.7.90)
        $block->remove($block->select( -type    => 'event',
                                       -data_re => "\/$title" . "\/" )
             ) ;
   }

#     print "\n";
#     print "crontab after remove\n";
#     print "---------------------\n";
#     print $ct->dump;
   return 0;
}

sub cronrmserial {
   #my $self      = shift;
   my $title     = $_[0];
   use Config::Crontab;
   my $ct = new Config::Crontab;
   $ct->read || die "could not read crontab. $?\n";;

   cronclean(\$ct, $title);

   $ct->write;
   exit 0;
}

sub cronlsserials {
   my $serials     = "";
   my $data        = "";
   my $hh          = "";
   my $mm          = "";
   my $dow         = "";
   my $cmd         = "";
   my $station     = "";
   my $duration    = "";
   my $titleoldfmt = "";

   use Config::Crontab;
   my $ct = new Config::Crontab;
   $ct->read || die "Konnte crontab nicht lesen. $?\n";;
   my $filmtitle = "";
   for my $event ( $ct->select () ) {
      $data = $event->data();
      if       ( $data =~ /^#\sRecord serial.*/ )  {
         $filmtitle = $data;
         $filmtitle =~ s/^#\sRecord serial\s\"//;
         $filmtitle =~ s/\s*\"$//;
      }  else  {
         if ($filmtitle)  {
            $mm       = $event->minute();
            $hh       = $event->hour();
            $dow      = $event->dow();

            $cmd      = $event->command();
            $cmd      =~ s/\"//g;

            $station  = $cmd;
            $titleoldfmt = $filmtitle . "_";
            $station  =~ s/$titleoldfmt//;
            $station  =~ s/\.avi.*$//;
            $station  =~ s/\`.*\`_//;  # old format (kalva <= 0.7.0)
            $station  =~ s/_\`.*\`//;
            $station  =~ s/.*mencoder.*\///;

            $duration = $cmd;
            $duration =~ s/.*-endpos\s//;
            $duration =~ s/\s-o\s.*//;

            $serials = "$serials title => \"$filmtitle\", station => \"$station\", duration => $duration, starttime => $hh:$mm:00, dow => \"$dow\", cmd => \"$cmd\";";

            $filmtitle = "";
         }
      }
   }
   select STDOUT;
   print "$serials";
   exit 0;
}

# bad name kept for backwardscompatibility :-/
sub atlsserials {
   return atls();
}

sub atls {
   my $job         = "";
   my $jobid       = "";
   my $movies      = "";
   my $movie       = "";
   my $starttime   = "";
   my $hh          = "";
   my $mm          = "";
   my $startdate   = "";
   my $cmd         = "";
   my $mencoder    = "";
   my $station     = "";
   my $duration    = "";
   my $titleoldfmt = "";
   my $filmtitle   = "";
   my @s           = ();
   select 0;
   my @jobs        = (`at -l`);
#print "\@jobs = @jobs\n";
   foreach ( @jobs )  {
      $job = $_;
      $cmd       = `at -c "$_" | tail -2 | head -1`;
      $cmd       =~ s/\n//g;

      if ( $cmd =~ /.*mencoder.*/  )  {
            $job =~ s/\n//g;
#print "cmd => $cmd";
#print "job => $job";
             $jobid   =  $job;
             $jobid   =~ s/\s.*//g;
             $starttime = $job;
#print "Starttime = $starttime \n"; 
             $starttime =~ s/\D*//g;
#print "=~ s/\D*//g => $starttime \n"; 
             $starttime =~ s/\s//g;
#print "=~ s/\s//g => $starttime \n"; 
             $starttime =~ s/^$jobid\s*//g;
#print "=~ s/$jobid//g => $starttime \n"; 
            $startdate = substr($starttime, 0, 4) . "." .
                          substr($starttime, 4, 2) . "." .
                          substr($starttime, 6, 2);
             $hh        = substr($starttime, 8, 2);
             $mm        = substr($starttime, 10, 2);
             $movie     = $cmd;
             $movie     =~ s/^.*-o //;
             $movie     =~ s/_\`.*$//;
             $duration  = $cmd;
             $duration  =~ s/.*-endpos\s//g;
             $duration  =~ s/\s-o.*//g;
             @s         = split("/", $movie);
             $station   = $s[-1];
             $filmtitle = $s[-2];

             $movies = "$movies";
             $movies = "$movies title => $filmtitle";
             $movies = "$movies, station => $station";
             $movies = "$movies, duration => $duration";
             $movies = "$movies, starttime => $hh:$mm:00";
             $movies = "$movies, startdate => $startdate";
             $movies = "$movies, cmd => $cmd";
             $movies = "$movies, jobid => $jobid;";
      }

## THIS COULD DEFENITLY BE IMPROVED... Through me a line if you can do this ;-)
#      $mencoder  = $cmd;
#      $mencoder  =~ s/^.*mencoder.*$/mencoder/g;
#      next unless ( $mencoder eq "mencoder" );
#print "mencoder = $mencoder\n";

   }
   select STDOUT;
   print "$movies";
   exit 0;
}

END { }       # module clean-up code here (global destructor)

1;

__END__

=head1 NAME

ModuleName - short discription of your program

=head1 SYNOPSIS

 how to us your module

=head1 DESCRIPTION

 long description of your module

=head1 SEE ALSO

 need to know things before somebody uses your program

=head1 AUTHOR

 Andreas Silberstorff

=cut
