#!/bin/sh
# Copyright (C) 2008 - 2013 vortexbox.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# Changelog:
#
# * Fri Dec 20 2013 Ron Olsen <ronolsen@comcast.net>
# - Always copy cover.jpg to folder.jpg in FLAC directory
#
# * Thurs Dec 19 2013 Ron Olsen <ronolsen@comcast.net>
# - Pass number of threads as an option to flac2mp3.pl
#
# * Mon Aug 12 2013 Ron Olsen <ronolsen@comcast.net>
# - Pass flac and mp3 directories as arguments.
#
# * Sun Mar 14 2010 Ron Olsen <ronolsen@comcast.net>
# - Check whether or not to embed coverart in the mp3 files.

function echolog {
echo "`date +'%m/%d/%Y %H:%M:%S'` - $1"
}

# Remove running flag if script is interrupted
trap "rm -f /etc/vortexbox/mirror-flac-mp3.running; exit" 1 2 3 15

LAMEOPT=`cat /etc/vortexbox/lameopt.txt`
THREADS=`cat /etc/vortexbox/numthreads.txt`

# Were we called correctly?
if [ -z "$1" -o -z "$2" ]; then
  echo "Usage: mirror-flac-mp3 <flacdir> <mp3dir>" >&2
  exit 1
fi
if [ ! -d "$1" ]; then
  echo "Error: $1 is not a directory" >&2
  exit 2
fi
flacdir="$1"/
mp3dir="$2"/
echo "flacdir is $flacdir"
echo "mp3dir is $mp3dir"

if [ ! -d "$mp3dir" ]; then
   mkdir -p "$mp3dir"
   if [ ! -d "$mp3dir" ]; then
      echo "Error: Couldn't create $mp3dir" >&2
      exit 3
   fi
fi

echolog "Mirroring FLACs to mp3 started."
touch /etc/vortexbox/mirror-flac-mp3.running

cd "$flacdir"
find . -name cover.jpg -type f -execdir cp -a cover.jpg folder.jpg \;
rsync -av   --include='*/' --include='cover.jpg' --include='folder.jpg' --include='*.txt'  --exclude='*' "$flacdir" "$mp3dir"
   
cd "$mp3dir"
find . -name *.tmp -type f -print0 | xargs -0 rm -f

if [ -f /etc/vortexbox/covermp3 ]
then
    # Embed cover art in the mp3 files
    mirrorargs=
else
    # Don't embed cover art in the mp3 files
    mirrorargs="--nocoverart"
fi
/usr/local/sbin/flac2mp3.pl $THREADS $mirrorargs --lameargs="--noreplaygain -h --nohist --quiet $LAMEOPT" "$flacdir" "$mp3dir" 

rm /etc/vortexbox/mirror-flac-mp3.running

echo ""
echo "Done."
echolog "Mirroring FLACs to mp3 done."
echo ""
