#!/usr/bin/perl

use strict;

my $command = shift;
my $mode = shift;

my $pidfile 	= "/usr/local/farm/data/PID";
my $sleepfile 	= "/usr/local/farm/data/SLEEP";
my $freezefile 	= "/usr/local/farm/data/FREEZE";

if ($command =~ /^sleep$/i) {
	if ($mode =~ /^on$/) {
		system("/bin/touch $sleepfile");
	} elsif ($mode =~ /^off$/) {
		system("/bin/rm -f $sleepfile");
	} else {
		&usage;
	}
} elsif ($command =~ /^freeze$/i) {
	if ($mode =~ /^on$/) {
		system("/bin/touch $freezefile");
	} elsif ($mode =~ /^off$/) {
		system("/bin/rm -f $freezefile");
	} else {
		&usage;
	}
} elsif ($command =~ /^kill$/i) {
	my ($pid,$pidfile,@files);


	my ($data_pid_dir) = "/usr/local/farm/data/pids";
	my ($master) = $data_pid_dir . "/MASTER";
	killpid ($master);
	sleep 2;

	opendir(DIR, $data_pid_dir ) || mydie("Can't open data directory $data_pid_dir!\n");
	@files = grep { /^[^\.]/ && -f "$data_pid_dir/$_" } readdir(DIR);
	closedir DIR;

print @files;
	foreach $pid (@files) {
		$pidfile = $data_pid_dir . "/" . $pid;
		killpid ($pidfile);
	}
#	} else {
#		print "farmathome does not appear to be running.\n";
#	}
} else {
	&usage;
}

exit;

#####################################################

sub killpid {
	my ($pidfile) = shift;

	my ($pid);
	if (-e $pidfile) {
		open (TMP, "< $pidfile");
		$pid = <TMP>;
		close TMP;
		# system("kill -s INT $pid");
		kill 2, $pid;
	}
}


sub usage {
	print "usage:  farmctl <sleep|freeze|kill> <on|off>\n";
	exit;
}
