#!/usr/bin/perl
# Filename:	airtunes
# Author:	David Ljung Madison <DaveSource.com>
# See License:	http://MarginalHacks.com/License/
# Description:	Play songs to an iTunes Airport via Airtunes
use strict;

##################################################
# Setup the variables
##################################################
my $PROGNAME = $0; $PROGNAME =~ s|.*/||;
my ($BASENAME,$PROGNAME) = ($0 =~ m|(.*)/(.+)|) ? ($1?$1:'/',$2) : ('.',$0);

my $DEFAULT = {
	justeport	=> "JustePort.exe",
	vol => 90,
	ip => '10.0.1.1',
	dec => {
		mp3 => "mpg123 -s",
		ogg => "oggdec -Q -R -o -",
		},
	};

##################################################
# Usage
##################################################
sub fatal {
	foreach my $msg (@_) { print STDERR "[$PROGNAME] ERROR:  $msg\n"; }
	exit(-1);
}

sub usage {
	foreach my $msg (@_) { print STDERR "ERROR:  $msg\n"; }
	print STDERR <<USAGE;

Usage:\t$PROGNAME [-d] <songs>
  Stream music to airtunes
  -ip #      IP address of Airport Express
  -vol #     Choose volume (1-100)
  -d         Set debug mode

USAGE
	exit -1;
}

sub parseArgs {
	my $opt = $DEFAULT;
	while (my $arg=shift(@ARGV)) {
		if ($arg =~ /^-h$/) { usage(); }
		if ($arg =~ /^-d$/) { $MAIN::DEBUG=1; next; }
		if ($arg =~ /^-vol$/) { $opt->{vol} = shift @ARGV; next; }
		if ($arg =~ /^-ip$/) { $opt->{ip} = shift @ARGV; next; }
		if ($arg =~ /^-mp3$/) { $opt->{dec}{mp3} = shift @ARGV; next; }
		if ($arg =~ /^-ogg$/) { $opt->{dec}{ogg} = shift @ARGV; next; }
		if ($arg =~ /^-justeport$/) { $opt->{justeport} = shift @ARGV; next; }
		if ($arg =~ /^-/) { usage("Unknown option: $arg"); }
		push(@{$opt->{songs}}, $arg);
	}
	usage("No songs?") unless $opt->{songs} && @{$opt->{songs}};

	# Normalize volume (from 0-100 to -144 to 0)
	$opt->{jvol} = int(1.44*$opt->{vol})-144;
	
	$opt;
}

sub debug {
	return unless $MAIN::DEBUG;
	foreach my $msg (@_) { print STDERR "[$PROGNAME] $msg\n"; }
}

##################################################
# Main code
##################################################
sub main {
	my $opt = parseArgs();
	
	foreach my $song ( @{$opt->{songs}} ) {
		print "$song\n";
		usage("No postfix - unknown song type?  [$song]")
			unless $song =~ /\.([^\.]+)$/;
		my $post = $1;
		usage("Unknown postfix [$post] for song: [$song]") unless $opt->{dec}{$post};
		system("$opt->{dec}{$post} $song | $opt->{justeport} - $opt->{ip} $opt->{jvol}");
		sleep 2;
	}
}
main();
