#!/usr/local/bin/perl
$|=1;

our $webdir = "/path/to/somewhere";
our $url;


sub cleanup {
  print STDERR "\nMOH CAUGHT ALRM!\n";
  $alive = 0;
  open PS,"/bin/ps -eo pid,args|";
  while(<PS>) {
    ($pid,$args) = split(" ",$_,2);

    if($pid ne $$ and $args =~ /.*?mpg123.*?http|.*?\/usr\/bin\/mpg123[\s\t]*$/) {
      my ($pid) = split;
      print STDERR "MOH KILL $pid\n";
      kill 9 => $pid;
    }
  }
  close PS;

}



while(1) {
  print STDERR "\n\nMOH STREAMER LOOP\n\n";
  system("/bin/rm -fr $webdir/restartmoh");
  my $url = `/bin/cat $webdir/mohurl`;
  $url =~ s/[\r\n\s]*//smg;
  my $player = "/usr/bin/mpg123 -q -m -f 8192 -s --mono -r 8000 $url";
  
  close PIPE;
  $pid = open PIPE,"$player|";
  $SIG{ALRM} = \&cleanup;
  alarm(5);
  $buf = undef;
  $alive = 1;

    
    eval {
      while($alive and read(PIPE,$_,2048)) {
	print $buf;
	alarm(0);
	$x++;
	if($x >= 20) {
	  $x = 0;
	  if(-f "$webdir/restartmoh") {
	    alarm(0);
	    system("/bin/kill -14 $$");
	  }
	}
	alarm(5);
	$buf = $_;
      }
      alarm(0);
    };

  
  alarm(0);
  close PIPE;
}

