#!/usr/bin/perl

##################################################
#
# GiantDisc mp3 Jukebox
# 
# © 2000-2002, Rolf Brugger
#
##################################################

# Recording timer script
#
# - starts recording sessions
# - creates new recording jobs
# - lists existing recording jobs
# - removes existing recording jobs
# - subscribes itself to "at" and "cron"



use lib '/home/music/bin';
use strict;
use gdparams;
use gdgentools;
use DBI;
use Getopt::Long;

### Init constants
my $dbh;
my $mp3base = gdparams::gdbase();		# music files base
my $dirbase = "$mp3base/browse";   #old: cwd();

my ($par_help, $par_dbhost, $par_start, $par_list, $par_create, $par_remove, $par_time, 
    $par_date, $par_length, $par_weekly, $par_daily);

$Getopt::Long::autoabbrev=1;
GetOptions(
	"help" 		=> \$par_help, 
	"dbhost:s" 	=> \$par_dbhost,
	"start:i" 	=> \$par_start,
	"list"  	=> \$par_list,
	"create"	=> \$par_create,
	"remove:i"	=> \$par_remove,
	"time:s"	=> \$par_time,
	"date:s"	=> \$par_date,
	"length:i"	=> \$par_length,
	"weekly"	=> \$par_weekly,
	"daily"		=> \$par_daily
	);

if ($par_help){ printhelp();}
else{


  ### Open database connection
  #print ("### Open database connection\n");

  $dbh = DBI->connect("DBI:mysql:GiantDisc", "music", undef)
    or die "unable to connect to GiantDisc db";


  #######################
  ### function dispatcher

  if ($par_list){      ### list jobs
    my $sth = $dbh->prepare('SELECT * FROM recordingitem ORDER BY id');
    $sth->execute;
    my ($row);
    while($row = $sth->fetchrow_hashref){
      print(
         $row->{id}. "\t"
        .$row->{recdate}. "\t"
        .$row->{rectime}. "\t"
        .$row->{reclength}. "\t"
        .$row->{repeat}. "\t"
        .$row->{atqjob}. "\t"
    	."\n");
    }
    $sth->finish;
  }
  
  
  
  elsif ($par_create){  ### Create new job
    if (length($par_date)<8 || length($par_time)<5 || $par_length<1)
      {print"ERROR in --create parameters\n\n";printhelp();exit();};
    # get new id
    my $newid = get_free_id();
    
    # create record
    my $repeat="";
    if    ($par_weekly){ $repeat="w"; }
    elsif ($par_daily) { $repeat="d"; }
    
print("INSERT INTO recordingitem SET "
    	." id = $newid, "
    	." recdate   = '$par_date', "
    	." rectime   = '$par_time', "
    	." reclength =  $par_length, "
    	." repeat    = '$repeat'"
    	."\n");
    my $retval = $dbh->do("INSERT INTO recordingitem SET "
    	." id = $newid, "
    	." recdate   = '$par_date', "
    	." rectime   = '$par_time', "
    	." reclength =  $par_length, "
    	." repeat    = '$repeat'" );
    
    # create at-queue entry
    enqueue_at_job($newid);
  }
  
  
  
  elsif ($par_remove){ ### Remove job
    if ($par_remove<1)
      {print"ERROR in --create parameters\n\n";printhelp();exit();};
    # remove job from at queue
#    dequeue_at_job($par_remove);
    
    # remove record
    #print("DELETE FROM recordingitem WHERE id=$par_remove \n");
    my $retval = $dbh->do("DELETE FROM recordingitem WHERE id=$par_remove");
  }
  
  
  
  elsif ($par_start){  ### make a recording
    # get record
    
    # re-enqueue it if repeated
    
    # start recording
  }
  
  else{
    printhelp();
  }
  
  
  #print("### close database connection\n");
  $dbh->disconnect;
}
exit;

###############################################################################

sub get_free_id{
  my $sth = $dbh->prepare('SELECT id FROM recordingitem ORDER BY id');
  $sth->execute;
  my ($row);

  my $id=1;
  while($row = $sth->fetchrow_hashref){
    last if($id < $row->{id});
    $id++;
  }
  $sth->finish;
  
  return $id;
}

###############################################################################

sub enqueue_at_job{
  
  my ($recid, $date, $time) = @_;
  my $tmpcmd = "/tmp/at-command.txt";
  my $tmpout = "/tmp/at-output.txt";
  my $atjobnum;

  system ("echo \"ls > ls.txt\" > $tmpcmd");
#  system ("at -f $tmpout now + 1 hour > $tmpout 2>&1");
  
  open (ATRES, "< ".$tmpout)
    or die "Error: could not open at result file $tmpout\n";
    
  my $line;
  while(<ATRES>){
    $line = $_;
    print ($line);
    if ($line =~ /job\s+(\d+)\s+at.*/ ){
      $atjobnum = $1;
    }
  }
  close(ATRES);

  ### Update record $recid with actual job number $atjobnum
print('UPDATE recordingitem SET atqjob='.$atjobnum.' WHERE id = '.$recid."\n");
  my $retval = $dbh->do('UPDATE recordingitem SET atqjob='.$atjobnum.' WHERE id = '.$recid);
  if ($retval != 1){
    print "Error: could not update a single recording item";
  }
}

########################
### ARTIST directory ###
########################


sub make_artist_directory{ #
  my ($dirbase, $mp3base) = @_;

  my ($artist, $title, $artist_esc);
  
#print ("change to $dirbase \n");
#  chdir ("$dirbase \n");

  ### Get all distinct artist names
  my $artsth = $dbh->prepare(
          'SELECT DISTINCT artist FROM tracks ORDER BY artist'
#          'SELECT DISTINCT artist FROM tracks where artist like "talk %" ORDER BY artist'
	);
  $artsth->execute;

#  while($artrow = $artsth->fetchrow_hashref){
    ### make and change to directory
#    $artist = gdgentools::ascii2filename(gdgentools::iso2ascii($artrow->{artist}));
#    print ("Artist: $artist");
#    mkdir ("$dirbase/$artist", 0755);	# does nothing if dir exists already!


    ### Get all tracks of artist
#    $artist_esc = $artrow->{artist};	# escape double quotes (")
#    $artist_esc =~ s/"/\\"/g;
#    my $trksth = $dbh->prepare(
#      'SELECT title, mp3file FROM tracks WHERE artist LIKE "'.$artist_esc.'"'
#    );
#    $nbtracks=$trksth->execute;
#    print "  ($nbtracks tracks)\n";

#    while($trkrow = $trksth->fetchrow_hashref){
      ### create link
      #print ("link: $dirbase/$artrow->{artist}/$trkrow->{title} \t $mp3base/$trkrow->{mp3file}\n");
#      $mp3fp = `ls $mp3base/??/$trkrow->{mp3file}`;  # get full filename and path
#      chop($mp3fp);
#      $title = gdgentools::ascii2filename(gdgentools::iso2ascii($trkrow->{title}));
#      symlink ("$mp3fp", "$dirbase/$artist/$title.mp3");
#    }
#    $trksth->finish;


 # }
  $artsth->finish;


}

###############################################################################

sub printhelp{
print <<ENDOFFILE;
gdrecordingtimer.pl: Manager script for timed recordings from line in 

Options

--dbhost (string)   address or hostname of mysql database server
                    Default value: localhost    
           
--start (number)    Starts the specified recording job

--list              Lists the pending recording jobs

--remove (number)   Removes the specified job from the list

--create            Creates a new recording job entry in
                    the database.
                    It also subscribes the job as a cron job (if it is a 
                    repeated recording) or as at job (if it is a single 
                    recording)
                          
--time  (string)    Recording start. Always used in conjuction with --create
                    Format: HH:MM:SS  (seconds are ignored)
                    
--date (string)     Recording start. Always used in conjuction with --create
                    Format: YYYY-MM-DD 
                    
--length (number)   Recording length in seconds. Always used in conjuction 
                    with --create
                                  
--weekly            Repeat the recording weekly

--daily             Repeat the recording daily

Comments:
To make a timed recording, a recording job must be created 
(option --create). This makes a database entry and subscribes the 
recrding job as an "at" job.

The at-job (once it is activated) again calls this script with the 
option --start and the job id as parameter. If the recording is 
repeated daily or weekly, a new at job is automatically created again.

Example:
create a new recording job and enqueue it in the at job list. It will record one 
hour from line-in, and the recording will be repeated every week.
  gdrecordingtimer.pl --create --date 2002-05-23 --time 21:00:00 --length 3600 -weekly

list (pending) recording jobs
  gdrecordingtimer.pl --list

remove job 12
  gdrecordingtimer.pl --remove 12

ENDOFFILE
exit 0;
}

###############################################################################

