#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my $user   = $ARGV[0] ? $ARGV[0] : 'undef_user';
my $action = $ARGV[1] ? $ARGV[1] : 'object_cache_add';

if ( ( !$user ) || $user eq 'root' || ( !defined( getpwnam($user) ) ) ) {
    print "$user :: $0 invalid user\n";
    exit;
}

if ( $action !~ /^(object_cache_add|object_cache_remove)$/ ) {
    print "$user :: $0 invalid action $action\n";
    exit;
}

modify_limits('set');
chomp( my $command = qx{sudo -u $user /opt/eig_wp/wp-object-cache.sh $action} );
foreach ( split( "\n", $command ) ) {
    print "$user :: $0 $_\n";
}
modify_limits('unset');

sub modify_limits {
    my $task             = shift;
    my $limits_file_conf = "/etc/security/limits.d/99-performance-pl-$user.conf";
    if ( $task eq 'set' ) {
        qx{echo '${user} hard nproc 4096' > $limits_file_conf};
    }
    elsif ( $task eq 'unset' ) {
        if ( -f $limits_file_conf ) {
            unlink $limits_file_conf;
        }
    }
}
