#!/bin/bash
# Version("2.1.0.1")
# InformationalVersion("2.1.0.1")

cd /home/recording

lockfile=/tmp/nixxis_mp3.lock;
timedif=3
debug=1
STOPTIME=`date --date='240 minutes' +%s`


if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null; 
then
   trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT

        echo `date '+%b %d %H:%M:%S'` Starting MP3 conversion...>>/var/log/nixxis_mp3mix.log

        # Split file loop into subset based on starting Character
        # to not process too many files in one go
        for z in {0..9} {a..f}

        do

                # Locate files that haven't changed in $timedif minutes.
                for f in `nice -n 19 find /home/recording -name $z*.wav -type f -cmin +$timedif 2> /dev/null`

                do
                        CURRENT=`date +%s`
                        if [ $STOPTIME -lt $CURRENT ]
                                then 
                                echo `date '+%b %d %H:%M:%S'` Exiting because of time limit >>/var/log/nixxis_mp3mix.log
                                exit
                        fi

                # Create full path filename without the leading .wav
                VAR=`echo $f|awk -F".wav" '{ print $1}'`

                echo `date '+%b %d %H:%M:%S'` Processing $VAR.wav >>/var/log/nixxis_mp3mix.log 
            
                # Execute Lame to convert file.
                nice -n 19 /usr/bin/lame -S -V 4 -b 16 -q 4 $VAR.wav $VAR.mp3
                if [ "$?" -eq "0" ]
                        then
                        rm $VAR.wav
                                #echo `date '+%b %d %H:%M:%S'` $VAR.wav - done
                        else
                                echo `date '+%b %d %H:%M:%S'` $VAR.wav - failed >>/var/log/nixxis_mp3mix.log
                        fi

                                # Check if we have passed execution time or not

                        done
                done

                echo `date '+%b %d %H:%M:%S'` Finished MP3 conversion...>>/var/log/nixxis_mp3mix.log
                rm -f "$lockfile"
                trap - INT TERM EXIT
else
   echo `date '+%b %d %H:%M:%S'` "Failed to acquire lockfile: $lockfile." >>/var/log/nixxis_mp3mix.log
   echo `date '+%b %d %H:%M:%S'` "Held by PID: $(cat $lockfile)" >>/var/log/nixxis_mp3mix.log
fi

