#!/usr/bin/env perl

use strict;
use warnings;
use JSON::XS;
use Proc::ProcessTable;
use Sys::Syslog qw(:standard :macros);
use Data::Dumper;

my $uid_cache            = {};
my $lsphp_time           = time() - 3600;
my $other_time           = time() - 300;
my @user_whitelist_array = qw(root nf00wpbenchs);

my $user_whitelist = { map { $_ => 1 } @user_whitelist_array };

foreach my $user ( @{ decode_json(qx{whmapi1 list_users --output=json})->{data}->{users} } ) {
    next if $user_whitelist->{$user};
    $uid_cache->{ getpwnam($user) } = $user;
}

my $t = Proc::ProcessTable->new( 'cache_ttys' => 1 );

openlog( $0, 'cons,pid', 'user' );

foreach my $proc ( @{ $t->table } ) {
    if ( $uid_cache->{ $proc->uid } && $proc->ppid == 1 ) {
        $proc->{cmndline} =~ s/\s+//g;
        my $message = 'PID:' . $proc->pid . ' PPID:' . $proc->ppid . ' USER:' . $uid_cache->{ $proc->uid } . ' START_TIME:' . $proc->start . ' CMNDLINE:' . $proc->cmndline . ' EXEC:' . $proc->exec;
        if ( $proc->cmndline ne 'lsphp' ) {
            next if ( $proc->{cmndline} =~ m#/usr/local/cpanel# );
            my $rc = kill 'SIGKILL', $proc->pid;
            syslog( 'info', '%s', "$message SIGKILL:$rc" );
        }
        elsif ( $proc->start < $lsphp_time ) {
            my $rc = kill 'SIGTERM', $proc->pid;
            syslog( 'info', '%s', "$message SIGTERM:$rc" );
        }
    }
}

sleep(1);

$t = Proc::ProcessTable->new( 'cache_ttys' => 1 );

foreach my $proc ( @{ $t->table } ) {
    if ( $uid_cache->{ $proc->uid } && $proc->ppid == 1 ) {
        $proc->{cmndline} =~ s/\s+//g;
        my $message = 'PID:' . $proc->pid . ' PPID:' . $proc->ppid . ' USER:' . $uid_cache->{ $proc->uid } . ' START_TIME:' . $proc->start . ' CMNDLINE:' . $proc->cmndline . ' EXEC:' . $proc->exec;
        if ( $proc->cmndline ne 'lsphp' ) {
            next if ( $proc->{cmndline} =~ m#/usr/local/cpanel# );
            my $rc = kill 'SIGKILL', $proc->pid;
            syslog( 'info', '%s', "$message SIGKILL:$rc" );
        }
    }
}

closelog();
