#!/usr/bin/perl
use strict;
use Sys::CpuLoad 'load';
use Data::Show;
use Fcntl ':flock';

my $pid_file = '/var/run/process.check.pid'; # Choose a suitable location

open my $fh, '>', $pid_file or die "Could not open PID file: $!";
print $fh $$; # Write current process ID to the file

# Attempt to acquire an exclusive lock (LOCK_EX) without blocking (LOCK_NB)
unless (flock $fh, LOCK_EX | LOCK_NB) {
    die "Another instance of the script is already running.\n";
}



# print '1 min, 5 min, 15 min load average: ',
#       join(',', load()), "\n";

my @la = load();
my $la = $la[0];
print $la . "\n";

# sleep 30;

if($la < 2.5){

	my @apps = (qw/clmapp dmapp oeapp prmapp psmapp/);
	foreach my $app (@apps){
		my $res = `/etc/init.d/$app status`;
		print $res . "\n";

		if($res =~ /Service not running|Process dead but pidfile exists/i){
			my $sres = `/etc/init.d/$app restart`;
			print $sres . "\n";
			# exit 0;
		}else{
			# exit 1;
		}
	}

}


# Release the lock and close the file when done (e.g., in an END block)
END {
    close $fh;
    unlink $pid_file;
}


1;
