#!/usr/bin/perl

use strict;
use warnings;
use JSON::XS;
use Proc::ProcessTable;
use Sys::Syslog qw(:standard :macros);
use Getopt::Long;
use Proc::Daemon;
use File::Slurp;
use Data::Dumper;

$0 = "proc-monitor";
my $user_check = '/tmp/.proc-monitor_time';
my $daemon     = Proc::Daemon->new(
    work_dir => "/root/",
    pid_file => "/var/run/proc-monitor.pid"
);
my $pid = $daemon->Status();
my ( $start, $stop, $status, $uid_cache );

GetOptions(
    "start"  => \&run,
    "status" => \&status,
    "stop"   => \&stop
);

sub stop {
    if ($pid) {
        print "Stopping pid $pid...\n";
        if ( $daemon->Kill_Daemon() ) {
            unlink $user_check if ( -f $user_check );
            print "Successfully stopped.\n";
        }
        else {
            print "Could not find $pid.  Was it running?\n";
        }
    }
    else {
        print "Not running, nothing to stop.\n";
    }
}

sub status {
    if ($pid) {
        print "Running with pid $pid.\n";
        exit 0;
    }
    else {
        print "Not running.\n";
        exit 1;
    }
}

sub run {
    if ( !$pid ) {
        print "Starting...\n";
        unlink $user_check if ( -f $user_check );
        $daemon->Init;
        while (1) {
            mem_usage_check();
            sleep(5);
        }
    }
    else {
        print "Already Running with pid $pid\n";
    }
}

sub mem_usage_check {
    my $lsphp_time   = time() - 3600;
    my $other_time   = time() - 300;
    my $mem_limit    = 1073741824;                   # 1 GByte
    my $passwd_mtime = ( stat('/etc/passwd') )[9];
    openlog( $0, 'cons,pid', 'user' );
    if ( ( !-f $user_check ) || ( $passwd_mtime > ( stat($user_check) )[9] ) || !$uid_cache ) {
        qx{touch $user_check};
        syslog( 'info', '%s', "Refreshing uid_cache" );
        undef $uid_cache;
        foreach my $user ( @{ decode_json(qx{whmapi1 list_users --output=json})->{data}->{users} } ) {
            if ( $user ne 'root' ) {
                $uid_cache->{ getpwnam($user) } = $user;
            }
        }
    }
    my $t = Proc::ProcessTable->new( 'cache_ttys' => 1 );
    foreach my $proc ( @{ $t->table } ) {
        if ( $uid_cache->{ $proc->uid } && $proc->rss >= $mem_limit ) {
            $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 . ' RSS:'
              . $proc->rss;
            my $rc = kill 'SIGKILL', $proc->pid;
            syslog( 'info', '%s', "$message SIGKILL:$rc" );
        }
    }
    closelog();
}
