#!/bin/bash
# chillout! (v0.3)
# lgpl'd (c) 2006 sk
# small tool to simply burn cd's out of some mp3's
# hope they got the right order, you should ensure
# that songs of an album are prefixed with 01, 02, 03 etc..

# options..
SPEED=8
DEV=/dev/hda
OPTS="burnfree"
FORMAT="mp3"

# commands/paths
NULL=/dev/null
CONVERT_CMD="mpg123 -w "
BURN_CMD="cdrecord dev=$DEV driveropts=$OPTS speed=$SPEED -dao -audio "

echo "chillout! (v0.3)"
echo "	lgpl'd (c) 2006 sk"
echo
echo "Will burn all $FORMAT's in current working dir/"
echo " with ${SPEED}x speed ($DEV [$OPTS])."
echo

# convert mp3
ls *.$FORMAT > $NULL 2>&1
if [ $? -eq 1 ]; then
	printf "\t~~~ No files (*.$FORMAT) found.\n"
	exit 1
fi

declare -a files
i=0
SIZE=0
for f in *.$FORMAT; do
	let i=$i+1
	fn="/tmp/${f/%$FORMAT/wav}"
	files[$i]=$fn
	echo -n "Track #$i is being converted.. "
	$CONVERT_CMD "$fn" "$f" > $NULL 2>&1 && echo "done. [$fn]"
	if [ $? -eq 0 ]; then
		locsize=`du "$fn" | sed 's/\s.*//'`
		SIZE=$[$locsize+$SIZE]
		echo "	Filesize: $locsize	Total: $SIZE"
	else
		echo "Error while converting track.. exit."
		exit
	fi
done

# count tracks
cnt=${#files[@]}

# append to cd burning cmdline..
for i in `seq $cnt`; do
	BURN_CMD="${BURN_CMD}-pad \"${files[$i]#/tmp/}\" "
done

# burn it..
err=0
pushd /tmp>$NULL
echo
echo "Attempting to burn CD ($[$SIZE/1024] MiB in $cnt tracks).."
echo "Press <Ctrl>+<C> to cancel (temporary files won't be removed then;"
echo "	cancel cdrecord to nevertheless let this happen)."
sleep 5
echo "${BURN_CMD}" | sh	# i'm just wondering (2:09am), why it fails on a simple $BURN_CMD (also with backticks)
if [ $? -gt 0 ]; then err=1; fi	# error flag
popd>$NULL
echo
echo

echo "Removing temporary files.."
# and finally remove temporary files
for i in `seq $cnt`; do
	rm "${files[$i]}"
done

# that's it.
if [ $err -eq 0 ]; then
	echo "chillout; that's it - have fun."
else
	echo "cdrecord failed.. check it's output above (maybe too big in size?)"
fi


