#!/usr/bin/perl

$SIG{'INT'}=\&intquit;

sub intquit { 
  print "Interrupt detected.\n"; exit
}

use gfio;
use JSON;

my $TM = time;
my $OTM = 0;
my $IPS = {};
my $PC = 0;

if (-e "protmail.dat") {
  $IPS = decode_json(gfio::content("protmail.dat"))
}

do {
  $TM = time;
  if ($TM-$OTM >= 3600) {
    $OTM = time;
    my @study = `journalctl -xe | grep "Failed password"`;
    for my $st (@study) {
      if ($st =~ /for invalid user ([a-zA-Z]+) from ([0-9\.]+)/) {
        store($1,$2)
      } elsif ($st =~ /for ([a-zA-Z]+) from ([0-9\.]+)/) {
        store($1,$2)
      }
    }
    gfio::create("protmail.dat",encode_json($IPS));
    system("/root/firewall.sh");
    print "Processed $PC ip's\n"; $PC=0;
  } else {
    sleep(100)
  }
} until (0);

sub store {
  my ($user,$ip) = @_;
  if ($ip eq '87.214.172.106') { return } # seringenhof
  if ($ip eq '84.53.97.66') { return } # UMCG
  if ($ip eq '37.97.233.157') { return } # Fats
  if ($ip eq '141.138.137.123') { return } # Amy
  if (!$IPS->{$ip}) {
    $IPS->{$ip}=$user; $PC++;
    my $rules = gfio::content("firewall.rules");
    $rules =~ s/\# DROP\n/\# DROP\n-A INPUT -s $ip -j DROP\n/;
    gfio::create("firewall.rules",$rules)
  }
}
