#!/usr/bin/perl

$DIR = $ENV{'ROOT'} || '/home/tom/station break';
$MIXERDEV = $ENV{'MIXERDEV'} || '/dev/mixer';
$AUDIODEV = $ENV{'AUDIODEV'} || '/dev/dsp';

$| = 1;
@RECENT = ();

chdir $DIR;

srand (time ^ $$ ^ unpack "%L*", `ps axww | gzip`);

print "[start $$]\n";
while (1) {
	while ((localtime)[2] < 8)
	{
		play (choose ('overnight'));
	}

	while (!is_it_stationid_time()) {
		play (choose ('music'));
		check_restart();
	}

	play (choose ('station ID'));
	$last_id_time = time;

	if ((localtime(time+600))[2] < 19 && ((localtime(time+600))[2] & 1)) {
		# before 7pm, odd hours only

		# words
		play (choose ('words'));
		check_restart();

		# station ID, need it or not
		play (choose ('station ID'));
		$last_id_time = time;

		# at least one music track
		play (choose ('music'));

		# music until next station ID time
		while (!is_it_stationid_time() &&
		       (time - $last_id_time < 3600)) {
			play (choose ('music'));
			check_restart();
		}
	} else {
		# after 7pm

		# music until end of this station ID window
		while (is_it_stationid_time() &&
		       (time - $last_id_time <= 1200)) {
			play (choose ('music'));
			check_restart();
		}

		# music until next station ID time
		while (!is_it_stationid_time() &&
		       (time - $last_id_time < 3600)) {
			play (choose ('music'));
			check_restart();
		}
	}
	check_restart();
}

sub check_restart
{
	if (-e "$ENV{'HOME'}/restart" && unlink ("$ENV{'HOME'}/restart")) {
		print "[restart $$]\n";
		exit 0;
	}
}

sub is_it_stationid_time
{
	(localtime)[1] < 10 || (localtime)[1] >= 50;
}

sub choose
{
	my ($section, $glob) = @_;
	if (!defined ($glob)) { $glob = '*.mp3'; }
	chomp (@mp3 = `find '$section/' -type f -name '$glob'`);
	my ($tries) = 0;
	while (++$tries < 7)
	{
		$n = int(rand($#mp3 + 1));
		if ($n > $#mp3)
		{
			$n = $#mp3;
		}
		if (!grep ($_ eq $mp3[$n], @RECENT))
		{
			last;
		}
	}
	unshift @RECENT, $mp3[$n];
	splice @RECENT, 5;
	return $mp3[$n];
}

sub play {
	my ($mp3) = @_;
	print ($mp3, "\n");
	system ('mpg123-auto', '-q', '-a', $AUDIODEV, $mp3);
#	select (undef, undef, undef, 1.5);
}
