#!/bin/bash

#Script to automate ripping a cd to .mp3 files
# mp3acd [artist_name][album_name]

# Prep ripping process. Make a temp directory and rip the cd.
logfile=`echo ~/cdtools_log`;
touch $logfile;
mp3_rip_dir="/backupa/mp3rip";
mp3_new_dir="/backupa/new_mp3s";
album_name=`echo $2|sed 's/\ /_/g'`;
artist_name=`echo $1|sed 's/\ /_/g'`;
old_pwd=`pwd`;

mkdir $mp3_rip_dir;
cd $mp3_rip_dir;
echo "Now in" $(pwd);

if
	echo "Now ripping";
	ripaudiocd $mp3_rip_dir;
	echo "Done ripping";
then
	echo `date` ":" "mp3 base rip completed" >> $logfile;
else
	echo `date` ":" "mp3 base rip failed.  Exiting." >> $logfile;
	exit 0;
fi

# Issue the command to compress the ripped files
# set track name

echo "Now entering MP3 compression";
track=1;
trackname=$artist_name"-"$album_name"-Track";

# Run the MP3 compression
for i in $( ls $mp3_rip_dir );
do
	if
		thistrack=$trackname$track".mp3";
		echo $thistrack;
		lame -b 192 -h $mp3_rip_dir/$i $mp3_rip_dir/$thistrack;
		track=$(($track+1));
	then
		echo `date` ":" "Compression successfully completed" >> $logfile;
	else
		echo `date` ":" "Compression failed.  Exiting." >> $logfile;
		exit 0;
	fi
done

# Move the newly created MP3s to another directory and clean up.
echo "Moving files";
if
	mkdir $mp3_new_dir;
	cd $old_pwd;
	if mv $mp3_rip_dir/*.mp3 $mp3_new_dir; then
		rm -Rf $mp3_rip_dir;
	fi
then
	echo `date` ":" "Successfully removed" $mp3_rip_dir >> $logfile;
else
	echo `date` ":" $mp3_rip_dir "unable to be removed. Exiting." >> $logfile;
	exit 0;
fi
