#!/afs/athena/contrib/perl/perl

require '/afs/athena/user/m/k/mkgray/perl/ftplib.pl';
$f = 'a';
`mkdir /tmp/dj`;

while(1){
	$song = &select_a_song;
	&zme("Fetching a song: $song\n");
	&get_it($song, $f);

	wait;
	$pid = fork();
	if($pid){
	#parent

	&zme("Playing $song\n");
	}
	else{
		&play_song($f);
		exit(0);
	}
	$f++;

}

sub select_a_song {
	srand;
	open(SONGS, "$ENV{'HOME'}/.songs");

	while(<SONGS>){
		chop;
		$song[$i++]=$_;
	}

	$s = rand($i-1);
	$song = $song[$s];
	$song;
}

sub zme {
        local($message) = @_;
        open (ZME, "|zwrite -n -q -d -s 'DJ' $ENV{'USER'}");
        print(ZME $message);
        close(ZME);
}


sub play_song {
	local($songname) = @_;

	`cat /tmp/dj/$songname > /dev/audio`;
	`rm /tmp/dj/$songname`;
}


sub get_it {
	local($file, $fn) = @_;;

&ftp'open('ftp.sdsu.edu', 'anonymous') || die "Can't open ftp connection: $ftp'ftp_error\n";
&ftp'get($file, "/tmp/dj/$fn") || die "Another stupid error: $ftp'ftp_error\n";
&ftp'close;
}
