#!/bin/bash
# Copyright (C) 2012-2013 Doug Asherman
#
# 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.
#
# 07/28/12  Call flac2ogg as child process
# 04/08/13 Remove hardcoded output file redirects

# if the sentinel flag exists, do not start another
# flac-to-ogg process
if [ -e /etc/x-stream/mirror-flac-ogg.running ];then
	echo "Flac mirroring to ogg already running"
	exit 1
fi

# if you pass in the directory, everything in that directory will 
# be converted by the flac2ogg script
if [ $1 ]; then
    curdir=$1
else
    curdir=`pwd`
fi

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

# change to the correct directory
# note: does the path separator have to be appended?
# I don't think so -- the flac2ogg script should handle that
cd $curdir

echolog ""
echolog "Starting encoding..."
echolog ""

# set up the flag to keep other mirror processes from running
touch /etc/x-stream/mirror-flac-ogg.running

# get all the directories with flac files in them, use uniq
# to delete the dupes.
# cd to the directory that you want to mirror, call the flac2ogg
# script. I think we're good here
for filepath in `find $PWD -name \*.flac | sed "s/[^\/]*$//" | uniq | sort`
do
	cd $filepath
	( .  /usr/local/sbin/flac2ogg.sh )
done

# get rid of the flag
rm /etc/x-stream/mirror-flac-ogg.running

echolog ""
echolog "Encoding complete...."
echolog ""