#!/usr/bin/perl


###### User configurable settings ######

my $limits_file = "/etc/security/limits.conf";
my $max_user_procs = 300;
my $max_swap_usage = 0.9; # 1 = 100%
my $max_mem_usage = 0.9;

###### End of configurable settings ######
###### Do not edit after this line ######

my $skip = 0;
my @fil;
use Linux::meminfo;
my %mem = get_meminfo;
my $mem_total = $mem{'MemTotal'};
my $swap_total = $mem{'SwapTotal'};
my $max_mem = sprintf("%.0f", $mem_total * $max_mem_usage);
my $max_swap = sprintf("%.0f", $swap_total * $max_swap_usage);
my $max_total_mem = $max_mem + $max_swap;
if(defined($max_total_mem))
{
	print "Setting up $limits_file..\n";
	&read_file;
	print "	Will set ".$max_total_mem."kib as maximum memory usage by any one user.\n";
	&add_to_file;
	print "Done.\n";
}

sub add_to_file
{
	use FileHandle;
	my $fh = new FileHandle "> $limits_file";
	my @array;
	foreach my $linje (@fil) { push(@array,$linje); }
	push(@array,"## Automagic config, do not edit, edited by \/etc\/init.d\/default_limits ##\n");
	push(@array,"*	hard	nproc	$max_user_procs\n");
	push(@array,"*	hard	as	$max_total_mem\n");
	push(@array,"## End automagic config ##\n");
	foreach my $line (@array)
	{
		if (defined $fh)
		{
			print $fh $line;
		}
		else
		{
			print "E: Filehandle is closed...Probably $limits_file does not exist.\n";
		}
	}
	undef ($fh);
}


sub read_file
{
	open(INNFIL,"$limits_file"); 
	my @file_content = <INNFIL>;
	close(INNFIL);
	foreach my $line (@file_content)
	{
		if ($line =~ m/^## Automagic config, do not edit, edited by \/etc\/init.d\/default_limits ##/) { $skip = 1; }
		if ($line =~ m/^## End automagic config ##/) { $skip = 0; }
		if ($skip == 0)
		{
			unless ($line =~ m/^## End automagic config ##/) { push(@fil, $line); }
		}
	}
}


