#!/bin/bash
##############################################################################
# Copyright (C) 2008 - 2015 x-stream.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.
#
# Name: mirror-cd-to-mp3
#
# Usage: mirror-cd-to-mp3 flacdir
#
# Get coverart for the FLAC album in flacdir, if necessary,
# then mirror the FLAC files in flacdir to mp3.
#
# Author: Ron Olsen <ronolsen@comcast.net>
#
# Date: Fri May 20 2011
# Version 1.0
#
##############################################################################

# Mirror specified FLAC directory to mp3


if [ $# -ne 1 ]
then
    echo "Usage: mirror-cd-to-mp3 flacdir"
    exit 1
fi

if [ ! -d "$1" ]
then
    echo "Error: $1 is not a directory"
    exit 2
fi

#echo "/usr/local/sbin/mirror-cd-to-mp3 $1"

flacdir="$1"
mp3dir=`echo $flacdir | sed -e "s;/flac/;/mp3/;" -`

#echo "FLAC dir is $flacdir"
#echo "mp3 dir is $mp3dir"

# Get cover art for FLAC dir

#echo "Getting cover art for $flacdir"
if [ ! -f "$flacdir/cover.jpg" ]
then
    /opt/x-stream/covergrabber.php "$flacdir"
fi

if [ -f "$flacdir/cover.jpg" ]
then
   #echo "copying $flacdir/cover.jpg to $flacdir/folder.jpg"
   cp -a "$flacdir/cover.jpg" "$flacdir/folder.jpg"
fi

#echo "Mirroring FLAC files in $flacdir to mp3 in $mp3dir"

if [ ! -d "$mp3dir" ]
then
    mkdir -p "$mp3dir"
fi
if [ -f "$flacdir/cover.jpg" ]
then
    cp -a "$flacdir/cover.jpg" "$mp3dir/cover.jpg"
    cp -a "$mp3dir/cover.jpg" "$mp3dir/folder.jpg"
fi

LAMEOPT=`cat /etc/x-stream/lameopt.txt`
lameargs="--noreplaygain -h --nohist --quiet $LAMEOPT"

if [ ! -f /etc/x-stream/covermp3 ]
then
    mirrorargs="--nocoverart"
else
    mirrorargs=
fi
    
#echo "Invoke flac2mp3.pl $mirrorargs --lameargs=$lameargs $flacdir $mp3dir"
echo "$(/bin/date): Mirror of FLAC files in $flacdir to mp3 in $mp3dir started."
/usr/local/sbin/flac2mp3.pl $mirrorargs --lameargs="$lameargs" "$flacdir" "$mp3dir" 
echo "$(/bin/date): Mirror of FLAC files in $flacdir to mp3 in $mp3dir completed."