#!/usr/bin/perl -w -I/usr/local/bin

# Script to be run from cron that finds .wav files and quietly
# converts them to mp3.

use strict;
use English;
use Fcntl;
use lib "/usr/local/bin";
use Env;
use mp3;
use pidfile;

local $debug = 1;
local $LOCKFILE = "/var/run/mp3enc.run";
local $pid = 0;

print &mp3_environment if $debug;


unless ($EUID == 0)
{
  print (STDERR "Must be run as root. Aborting.\n");
  exit 1;
}

unless (&create_pidfile($LOCKFILE))
{
  print (STDERR "Cannot create lockfile $LOCKFILE\n");
  exit 1;
}

if($pid = fork())
{
  LogMessage "mp3enc.pl: Daemon started\n"; 
  exit 0;
}

setpgrp;
setpriority(0,0,20);

for(;;)
{
  LogMessage "INFO: Starting Serial Encode Run";

  &serial_encode;

  LogMessage "INFO: End of Serial Encode Run";

  sleep (300); # Have five mins off
}


sub serial_encode
{
  LogMessage "mp3enc.pl: searching for wav files in $mp3::DIR";

  my @files = split "\n", `find $mp3::DIR -name \*.wav -print`;
 
  foreach my $file (@files) 
  {
    LogMessage("INFO: START Encoding $file");

    unless (&create_pidfile("$file.mp3enc.lck"))
    {
      next;
    }

    system qq($mp3::ENCODER "$file");

    if($?)
    {
      LogMessage "ERROR: Problem encoding file [$file] bladeenc returned code ($result)\n";
      next;
    }

    LogMessage "INFO: Removing wav file $file\n";

    unlink $file;

    &remove_pidfile("$file.mp3enc.lck");

    LogGeneral("INFO: STOP Encoding: $file");
  }
}

1;