#!/usr/bin/env bash
#
# Copyright 2008, Centova Technologies Inc.
#
# This script is used to re-encode MP3s to the specified parameters.  Requires
# that lame be installed on your system.
#
# usage:
#   reencode.sh bitrate samplerate channels filenames...
#

# change this if lame is not in your path
LAMEPATH=lame

SELFPATH=`dirname $0`
TMPDIR=$SELFPATH/vhosts/tmp

[ $# -lt 4 ] && echo "usage: $0 bitrate samplerate channels filenames..." && exit 1

HASLAME=`which $LAMEPATH`
[ -z "$HASLAME" ] && echo "Could not find lame encoder" && exit 1

BITRATE="$1"
shift
SAMPLERATE=`echo "$1" | awk '{print $1 / 1000}'`
shift
CHANNELS="$1"
shift

CHANARG=""
[ $CHANNELS -eq 1 ] && CHANARG="-a"
[ $CHANNELS -eq 2 ] && CHANARG="-m s"

rm -rf $TMPDIR
mkdir -p $TMPDIR

ID3PHP=$SELFPATH/../system/id3.php

while [ ! -z "$1" ]; do
	rm -f $TMPDIR/_reencode_tmp.mp3
	echo '#!/bin/sh' > $TMPDIR/_reencode_tmp.sh
	php -q $ID3PHP "esc:'$LAMEPATH --tt '%title%' --ta '%artist%' --tl '%album%' --ty '%releaseyear%' --tg '%genre%' --mp3input -h $CHANARG -b $BITRATE --resample $SAMPLERATE '%filename%' $TMPDIR/_reencode_tmp.mp3" "$1" >> $TMPDIR/_reencode_tmp.sh
	chmod a+x $TMPDIR/_reencode_tmp.sh
	cat $TMPDIR/_reencode_tmp.sh
	$TMPDIR/_reencode_tmp.sh

	[ -f $TMPDIR/_reencode_tmp.mp3 ] && mv $TMPDIR/_reencode_tmp.mp3 "$1"
	
	shift
done

rm -rf $TMPDIR
