#!/bin/sh

# Copyright (C) 1999 Nathaniel Smith <njs@uclink4.berkeley.edu>
# Copyright (C) 1999, 2000 Robert Woodcock <rcw@debian.org>
# This code is hereby licensed for public consumption under either the
# GNU GPL v2 or greater, or Larry Wall's Artistic License - your choice.
#
# You should have recieved a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

# Copyright for this work is to expire January 1, 2010, after which it
# shall be public domain.

# TODO:
#  - Clean up so uses fewer temp files
#  - Add more error checking

# KNOWN BUGS:
#  - Not much error checking, esp. of arguments
#  - Submitted via: line is created by template, when it really should be in send.
#    Oh well.
#  - Very slow, relatively speaking, but this is probably acceptable.
#  - This code is disgusting in parts, but then, it's a shell script.

VERSION=0.2
NAME=cddb-tool

#return codes
BAD_SYNTAX_ERR=10  # invalid CDDB file
NO_TMP_ERR=11      # can't create a temp file
NO_MATCH_ERR=12    # try submitting one
LOOKUP_ERR=13      # problem connecting to cddb server
EMPTY_QUERY_RESPONSE=14	# query response = "", (probably no net connection)

TMP=/tmp   # where to put tempfiles

# assume a reasonable default if $WGET is undefined
if [ "$WGET" = "" ]; then
	WGET=wget
fi

usage() {
	  cat << EOF
$NAME version $VERSION
usage: one of:
  $0 parse file -i|-d|-a|-t num|-c|-p
  $0 template
  $0 send [file] address
  $0 read server user host disc-id genre
  $0 query server user host disc-id tracks
  $0 help
EOF
}

help() {
	cat << EOF
$NAME version $VERSION
A toolbox for doing cddb related stuff

Usage: $0 command [command_options]

Commands:
  parse file option
	Get data out of a cddb file; use - for stdin
	options: (use 1 and only 1)
	id		prints disc id
	album		prints album title
	track num	prints title of track num
	artist	prints artist
	category	prints category
	cddbgenre	synonym for category
	all		parse file and dumps to stdout in a form
			source'able by the shell
  send [file] address
	Mails file file (or stdin of no file specified)
	to specified address, using correct format.  Category should
	be one of blues, classical, country, data, folk, jazz, newage,
	reggae, rock, soundtrack, misc.
  template disc-id tracks
	Generates a template (empty) cddb file to stdout.  The command
	line should be essentially the output of cd-discid.
  query server user host disc-id tracks
	Looks up disc on server (should be of form "http://host/cddb/cddb.cgi")
	remainder of command line is in the same form as that returned
	by the cd-discid program.  
  get server user host disc-id genre
	CDDB file is dumped to stdout. File will contain an extra
	#CATEGORY= line, which leaves it a valid CDDB file but which will
	be recognized by parse and send commands. Uses wget, so if you
	need to use a proxy then just configure wget to do so. user and
	host will be used for identifying ourselves to the CDDB server.
  help  
	Display this.
EOF
}

# takes 1 argument, a filename, and dumps out a sh parseable version
parse() {
	if [ "$1" = "-" ]; then	
		# for convenience, so we can grep it multiple times
		TMPFILE=$(mktemp $TMP/$NAME.parsing.XXXXXX) || exit $NO_TMP_ERR
		cat > $TMPFILE
		CDDBFILE="$_PARSE_TMPFILE"
	else
		CDDBFILE="$1"
	fi
		
	set -e
	# names chosen to match usage in abcde code
	DISCID=$(grep ^DISCID= "$CDDBFILE" | cut -f2 -d= | tr -d \[:cntrl:\])
	DARTISTALBUM=$(grep ^DTITLE= "$CDDBFILE" | cut -f2- -d= | sed 's- / -~-g')
	DARTIST=$(echo $DARTISTALBUM | cut -f1 -d~ | sed 's,\\,\\\\,g;s,\([\"\$\`]\),\\\1,g' | tr -d \[:cntrl:\])
	DALBUM=$(echo $DARTISTALBUM | cut -f2 -d~ | sed 's,\\,\\\\,g;s,\([\"\$\`]\),\\\1,g' | tr -d \[:cntrl:\])
	CDDBGENRE=$(grep '^#CATEGORY=' "$CDDBFILE" | cut -f2- -d=)

	set +e
	echo DISCID=\"$DISCID\"
	echo DALBUM=\"$DALBUM\"
	echo DARTIST=\"$DARTIST\"
	echo CDDBGENRE=\"$CDDBGENRE\"
	NUMTRACKS=$(grep -E '^TTITLE[0-9]+=' "$CDDBFILE" | wc -l)
	CURRTRACK=0
	while [ "$CURRTRACK" -lt $NUMTRACKS ]; do
		CURRTRACKM1=$CURRTRACK # Track minus 1 (cddb numbers from 0)
		CURRTRACK=$(expr $CURRTRACK + 1)
		echo -n "TRACK${CURRTRACK}=\""
		grep ^TTITLE${CURRTRACKM1}= "$CDDBFILE" | cut -f2 -d= | sed 's,\\,\\\\,g;s,\([\"\$\`]\),\\\1,g' | tr -d \[:cntrl:\]
		echo \"
	done
	# clean up
	if [ -f $_PARSE_TMPFILE ]; then
		rm -f $_PARSE_TMPFILE
	fi
}

COMMAND=$1
shift
case $COMMAND in
parse)
	TMPFILE=$(mktemp $TMP/$NAME.parsed.XXXXXX) || exit $NO_TMP_ERR
	parse "$1" > "$TMPFILE"
	. "$TMPFILE"
	shift
	case "$1" in
	id) echo "$DISCID" ;;
	album) echo "$DALBUM" ;;
	track) 
		shift
		if [ "$1" = "" ]; then 
			echo "$0: Error: parse track needs a number" >&2
			rm -f $TMPFILE
			exit $BAD_SYNTAX_ERR
		else 
			eval echo "\$TRACK$1"
		fi ;;
	artist) echo $DARTIST ;;
	category|cddbgenre) echo $CDDBGENRE ;;
	all) cat "$TMPFILE" ;;
	*) echo "$0: Error: unknown parse option $1" >&2; rm -f $TMPFILE; exit $BAD_SYNTAX_ERR ;;
	esac
	rm -f "$TMPFILE"
	;;

template)
	DISCID="$@"
	DISCNUM=$1
	echo '# xmcd CD database file'
	echo '#'
	echo '# Track frame offsets:'
	NUMTRACKS=$2
	for x in $(seq 3 $(expr $NUMTRACKS + 2))
	do
		echo -e "#\t$(echo "$DISCID" | cut -f$x -d' ')"
	done
	x=$(expr $x + 1)
	LENGTH=$(echo "$DISCID" | cut -f$x -d' ')
	echo "#"
	echo "# Disc Length: $LENGTH seconds"
	echo "#"
	echo "# Submitted via: $NAME $VERSION"
	echo "#"
	echo "#blues,classical,country,data,folk,jazz,newage,reggae,rock,soundtrack,misc"
	echo "#CATEGORY=misc"
	echo DISCID="$DISCNUM"
	echo "DTITLE=Unknown Artist / Unknown Album"
	# TTITLE0 -- TTITLEn
	for x in $(seq 1 $NUMTRACKS)
	do
		echo "TTITLE$(expr $x - 1)=Track $x"
	done
	echo "EXTD="
	# EXTT0 -- EXTTn
	for x in $(seq 1 $NUMTRACKS)
	do
		echo "EXTT$(expr $x - 1)="
	done
	echo "PLAYORDER="
	;;

send) # cddb-tool send [filename] email@address
	if [ "$2" != "" ]; then
		FILE="$1"
		ADDRESS="$2"
	else
		TMPFILE=$(mktemp $TMP/$NAME.sending.XXXXXX) || exit $NO_TMP_ERR
		cat > "$TMPFILE"
		FILE="$TMPFILE"
		ADDRESS="$1"
	fi
	grep -v "^#CATEGORY=" "$FILE" | mail "$ADDRESS" -s "cddb $($0 parse $FILE category) $($0 parse $FILE id)"
	if [ "$TMPFILE" != "" ]; then
		rm -f "$TMPFILE"
	fi
	;;

query) # cddb-tool query serverurl user host discid...
	SERVER="$1"
	USER="$2"
	HOST="$3"
	HELLOINFO="$USER+$HOST+$NAME+$VERSION"
	shift 3
	TRACKINFO="$@"
	TRACKINFOPLUS=$(echo $TRACKINFO | tr ' ' '+')
	RESULTS=$($WGET -q -O - "$SERVER?cmd=cddb+query+$TRACKINFOPLUS\&hello=$HELLOINFO\&proto=3") || exit $LOOKUP_ERR
	echo $RESULTS | tr '\r' '\n' | tr -s '\n' | sed 's/^ //g'
	;;

read) # cddb-tool read serverurl user host genre discnumber
	SERVER="$1"
	USER="$2"
	HOST="$3"
	CATEGORY="$4"
	DISCID="$5"
	HELLOINFO="$USER+$HOST+$NAME+$VERSION"
	$WGET -q -O - $CDDBDATA "$SERVER?cmd=cddb+read+$CATEGORY+$DISCID\&hello=$HELLOINFO\&proto=3" 2>/dev/null
	;;

	help) help ;;
	*) usage ;;
esac
