#!/usr/bin/perl -w
# (C)2005 Alex Hudson, GPLv2+
use strict;
use warnings;
use POSIX ":sys_wait_h";

my $pidfile = '/var/run/hula/hulamanager.pid';

my $pid = 0;

if (! -e $pidfile) {
	warn "hula isn't running";
	exit;
}
$|++;

open (PID, $pidfile) or die "Cannot examine pid!";
$pid = <PID>;
close (PID);

sub hula_running { return -d "/proc/$pid"; }
sub hula_kill    { `hulamanager -s`; }
sub hula_wait {
	my ($limit, $count) = ($_[0], 0);
	while (hula_running() && ($count < $limit)) {
		select (undef, undef, undef, 0.25);
		print '.' if (($count % 10) == 0);
		$count++;
	}
}

if (! hula_running()) {
	print "hula isn't running";
	exit;
} else {
	print "Stopping ...";
	hula_kill();
	hula_wait(100);
	if (hula_running()) {
		hula_kill();
		hula_wait(150);
	}
}

if (hula_running()) {
	print "Can't stop hula :(\n";
	exit -1;
} else {	
	print "hula stopped.\n";
	exit 0;
}
