#!/usr/bin/perl
use strict;
use warnings;
use IO::File;
use Cwd 'chdir';

my $dir = "/var/www/attach";

local(*DIR);
opendir(DIR,$dir);
my @files = readdir(DIR);
closedir(DIR);

my %ipcounts;
my $daily_max = 15;
my $report_max = 5;

my @protect_ip = ('68.61.179.225', '76.112.146.41', '68.42.122.142', 
                  '68.61.176.86');
my %protected;
foreach my $file (sort @files)
  {
    my $empty_subject = "";

    if($file =~ /^msg\-(_?\d+_\w+_\d+)\-\d+/)
      {
        if(-s "$dir/$file" < 180)
          {
            system("rm $dir/$file");
            next;
          }
        my $date = $1;

        # This is a candidate
        my $fh = IO::File->new("$dir/$file");
        next if(!defined $fh);

        while(my $line = <$fh>)
          {
            $empty_subject = "started" if($line =~ /^Subject:\s*$/i);

            if($line =~ /^FromIP:\s+([\d\.\:a-f]+)/i)
              {
                my $ip = $1;

                my $is_protected = "";
                foreach my $protect (@protect_ip)
                  {
                    if($ip eq $protect)
                      {
                        $protected{$file} = 1;
                        $is_protected = 1;
                      }
                  }
                next if($is_protected);
                # Note this one
                $ipcounts{$date} = {}
                             if(!defined $ipcounts{$date});
                $ipcounts{$date}->{$ip} = []
                             if(!defined $ipcounts{$date}->{$ip});
                push @{$ipcounts{$date}->{$ip}},$file;
                last;
              }
            elsif($empty_subject eq "started" && 
                    $line =~ /^Body:\s*$/i)
              {
                $empty_subject = "sofar";
              }
            elsif($empty_subject eq "started" &&
                    $line =~ /^Body:\s*\S+/i)
              {
                $empty_subject = "full";
              }
            elsif($empty_subject = "sofar" && $line =~ /\S/)
              {
                $empty_subject = "full";
              }
          }
      }
    system("rm $dir/$file") if($empty_subject eq "sofar");
  }

foreach my $date (sort keys %ipcounts)
  {
    # Each date reports
    foreach my $ip (sort {$#{$ipcounts{$date}->{$b}} <=>
                          $#{$ipcounts{$date}->{$a}}} keys %{$ipcounts{$date}})
      {
        last if($#{$ipcounts{$date}->{$ip}} < $report_max);
        if($#{$ipcounts{$date}->{$ip}} > $daily_max)
          {
            foreach my $file (@{$ipcounts{$date}->{$ip}})
              {
                # print "rm $dir/$file\n";
                system("rm $dir/$file");
              }
          }
        else
          {
            # print "$date $ipcounts{$date}->{$ip} $ip\n";
          }
      }
  }


my @flags = ('vuitton','anel-bags','tangjin3600','coach--outlet',
      'nike-air','payday loans','airjordan','coachnomachi','rxpills',
      'shoesforsale','no prescription','freewebs.com',
      'viagra','shoesforsale','solejordanshop.com',
      'christianlouboutin','forsale.com','uggboot','onlinecheap',
      'Hong Kong-based startup','NBA Game table of Governors',
      'TIBCO Software chairman',
      ' ugg','\[url=http:',' UGG',
      'Mulberry Handbags','cheapghdsukoutlet','paulpottsofficial',
      'european-mediaculture','ruhr-connect','loveepicentre',
      'Louis Vuitton handbags','quenellesgraphiques',
      'spansklararforeningen',
      'oakley/oakley','/oakley/',
      'uggstyles','factoryoutlet','Subject: \S\S\S\S\S\S\S\S\S',
      'Bitcoin','oakley sunglas','harrietvstheworld',
      'lapinbrun','parfum-discount','artandcraftmasters',
      'fotofile.eu','hannawinery','Michael Kors',
      'les-marguerites','Chaussures_Nike_Air_Max',
      'babyliss',' fuck ','Nike Air',
      'Sini White','\.asp','\.php',' 49ers ',' NFL ',' Nike ',
      'Soccer Jerseys','minnesota twins',' nfl ',',nfl ',' nfl,',
      '\-MLB\-','\-NBA\-','\-AFL\-','\-NHL\-','\-NFL\-',
      ' Reebok ',' air max ',' burberry ',' canada hockey ',
      'www\.tattiemoon\.',' converse new',' coach outlet ',
      ' asics gel ',' chanel london ',' gucci ',
      ' jordan shoe',' adidas ',' canada goose ',
      ' adidas ','canada goose','gucci ','ray ban',
      'air jordan','chanel keychain','cheap jordan',
      'cosmetics online','urban decay','lorac palette',
      '27\.150\.230\.','59\.58\.156\.','175\.44\.46\.',
      '117\.26\.81\.','112\.109\.234\.212','27\.153\.239\.114',
      '121\.205\.238\.232','27\.159\.239\.65','117\.26\.195\.193',
      '27\.153\.235\.2','\.penonsale\.','120\.37\.206\.32',
      ' prada ','91\.207\.7\.110','27\.153\.234\.226',
      '222\.77\.206\.193','140\.237\.15\.211','hawaii-stuff',
      'tribos.biz','CANADA GOOSE','lebronjames-shoes','gcc.us.com',
      ' nike ','adriobranco','2a00:1210:fffe:196::1',
      '112\.111\.183\.208','112\.111\.166\.2','175\.42\.83\.141',
      '175\.42\.83\.141','175\.42\.81\.200','62\.210\.129\.235',
      ' Saint Laurent ','58\.22\.139\.167','58\.22\.150\.236',
      '80\.116\.30\.100','183\.252\.2\.219','socialwebpromotions',
      'game for android','37\.187\.93\.152','121\.205\.214\.129',
      '110\.85\.75\.198','36\.248\.167\.181','cb8isesb',
      'Seiko Watches','117\.26\.248\.64','192\.187\.115\.98',
      ' jimmy choo ','110\.89\.40\.242','91\.197\.49\.162',
      '175\.44\.53\.8','mimsa.com',' oakley ','newbalance',
      ' hermes ','marc jacobs','louboutin',' kors ',
      'ralph lauren',' lacoste ',' perfumes ','27\.159\.253\.183',
      'archeage','198\.15\.178\.42',' chanel ','120\.43\.11\.227',
      '72\.46\.141\.50','72\.46\.128\.122','72\.46\.141\.50',
      ' jersey',' jerseys',' jordan ',' mont blanc ',' lipstick mac',
      ' tiffany ','208\.66\.77\.','72\.46\.153\.202','63\.141\.249\.27',
      '192\.187\.114\.154','76\.164\.226\.131','104\.194\.26\.',
      '76\.164\.234\.138','72\.46\.153\.203','208\.110\.84\.34',
      '142\.54\.173\.90','72\.46\.140\.101','173\.208\.182\.74',
      '91\.200\.12\.18','No Prescription','Erectile Dysfunction',
      '193\.201\.224\.68','110\.89\.26\.5','120\.40\.144\.104',
      '27\.150\.228\.147','north face','Louis Vuitton',
      '220\.161\.169\.',' FiFa 15 ','69\.30\.254\.','107\.150\.47\.138',
      '76\.164\.192\.',
      '\.cricket/', '\.bid/', '\.top/', '\.kim/',
      '\.trade/', '\.xyz/', '\.in/', '\.red/', '\.webcam/',
      '\.xyz/', '\.link/', ' porn ', 'bestinvest', 'shoeswebs', 
      'at least 300 visitors', 'in your city', 'cryptocurren', 
      'promoted as a resource', 'michaelwebdev', '\.ru ', 'in your town', 
      'a lot more traffic', '\.ru\/', 'steroids', 
      'appadultdating', 'Lightning Funnels', 'Natural Stress Solutions', 
      '\$10,000', 'POWERFUL and PRIVATE', 'last longer in bed', 
      'Chemist Warehouse', 'Win an iPhone', ' iPhone X ',
      ' High Potency ', ' casino ', ' professional copywriter ',
      ' traffic to your site', 'bitcoin', 'cryptocurren',
      ' win iphone', 'bit.ly/2PVgtFh', 'lead conversion expert',
      't optimized', 'prizeemail.online',      
      ' ClickBank ', ' CCTV ', 'onlineuniversalwork.com', ' backlinks ', ' passive income',
      'einkommen', 'moreleadsandsales', 'Einkommen', 'bogazicitente',
      'sms.i-link.us', 'ecuadortenisclub', 'vae.me', 'huit.re',
      'freeurlredirect.com', 'jtbtigers.com', 'SEO metrics', 
      'slimex365.com', 'links.wtf', 'search engine opt',
      'jtbtigers.com', 'business loan', 'nuratina.com',
      'Donate:', 'largeglobes', 'seoworks.co.uk', 'UK Digital Agency', 
      'sqribble.site', '.wordpress.com', 'revolutionary lead generation', 
      'website for free', 'Keto Diet', 'Surgical face masks', 
      'leading vape shop', 'SEX dating', 'Adult dating', 
      'line Casino', 'wteresources.com', 'guaranteed sales income',
      'wtex.org', 'surgical masks', 'automated trading system',
      'type of advertising', 'Phungcorsi@gmail.com', 'WTEBANK.COM',
      'turn around your business', 'cranial suture',
      'Link -', 'nothing will go wrong with your investments', 
      'You need business protection', 'TERMINATED WITHIN', 
      'leader in mobile gaming', 'Hello. And Bye', 
      'overnment authorized seller', 'Countess Louise of Savoy',
      'poems composed', 'EXPIRATION NOTIFICATION', 
      'Credit Default Swap', 'Business Interruption Insurance', 
      'handwritten by the author', 'fake id make', 
      'of typography', 'ndwritten book', 'buy assets', 
      'Increase Deep Sleep', 'this post ', 'handwritten publishers', 
      'of surviving European', 'Testaru', 'mostly in monasteries', 
      'quick boost in ranks and sales', 'research of documents', 
      'monuments related to deep', 'ritten on the parchment', 
      'or their samples written', 
      'marvellous chance to read', 
      'most painful problem that you want to solve the most', 
      'and was erased, and on cleaned', 
      'Lizeth Cangey', 
      'millions of companies', 
      'Duke de Montosier', 
      'online dating', 
      'top search engine rankings', 
      'which is carried out by the printing', 
      'email address has become a winner', 
      'fat burning formula', 
      'secular brotherhoods of scribes', 
      'came up with a horrible feeling', 
      'the top search engine rankings', 
      'only a few survived', 
      'omplete series LS, BD, YWM, Liluplane', 
      'precious recommendations he got', 
      'princess gained visiting your blog', 
      'scroll. Go to Code Form', 
      'One of the most skilled calligraphers', 
      'so expensive material', 
      'your website could use an upgrade', 
      'By the end of the 15th century', 
      'center yourself and clear your head', 
      'monthly sales revenue for your compan', 
      'Ellie loves setting aside time for internet researc', 
      'sales with Artificial Intelligence techniques', 
      'HaywardBeats', 
      'Century to a kind of destruction', 
      'airtight system to move web visitors', 
      'Egyptian papyri', 
      'billionaires and Fortune 500 companies', 
      'the spread of parchment', 
      'your products and services within 24 hours', 
      'wtedcp.com', 
      'assetstocapital.net', 
      'multiply your sales revenue', 
      'bought a car on PCP', 'wilfredrussell', 
      'drafts of literary works', 'Guirlande de Julie',
      'new texts were rewritten', 'Western Europe also formed', 
      'text and illustrations to wh', 'Fake ID',
      'virtual platforms performed best', ' magnificent secrets ',
      'the chess of love', 'ancient times was papyrus', 
      'my intimate photos as I ', 'triangle offense which',
      'need for help on this important concern', 
      'monthly on autopilot', 'low cost unsecured working capital', 
      'carry out his studies through your ideas', 'operate on a no win, no fee basis', 
      'worldtradeexchange', 
      'he is especially famous', 
      'generic levitra', 
      'Top Avana', 
      'rx pharmacy ', 
      'term manuscript', 
      'families make money', 
      'No cost, no card, no catch', 
      'Do I need you time and again I', 
      'commonly associated with', 
      'copperleife.com', 
      'NO PAY, PREMIUM or PAYLINK', 
      'term manuscript', 
      'often alone in my bedroom', 
      'does levitra take', 
      'text carrier and protective', 
      'results from social media', 
      'canadian drugs without prescription', 
      'research tadalafil', 
      'Preserved about 300 thousand', 
      ' levitra ', 
      'canadian pharmacies', 
      'tadalafil citrate', 
      'best online pharmacy', 
      'Cialis Super Active', 
      ' cialis for daily use', 
      'canadian pharmacy', 
      'manuscripts held onto', 
      'transaction of mutual benefit', 
      'guarantee that nothing will go wrong with your business', 
      'canadian prescriptions', 
      ' tadalafil ', 
      'alegra DXT plus', 
      'from lat. manus', 
      'Nice site https', 
      'erectile dysfunction', 
      'In the XIII-XV centuries', 
      'free hookup girls', 
      'online pet pharmacy', 
      'and in Ancient Russia', 
      'cheap pharmacy', 
      'order prescriptions online', 
      'the manuscript is called', 
      'introduce you to our program', 'cialis', 
      ' bridge fund ', 
      ' online pharmacy ', 
      'among them acquired', 
      'Thorazine', 
      ' drugs without prior prescription ', 
      'sildenafil citrate', 
      'captcha solver', 
      'Saliva Antigen Test', 
      'only a few have reached u', 
      ' sex pics', 
      'capacious positively',       'pcoming drama', 
      'Local Ranks organically', 
      ' want to meet you', 
      ' leave the war ', 
      'math games fireboy', 
      'a large city in the central ', 
      'glad to have found this web page', 
      ' is interested in you', 
      'dimensionless bluetooth', 
      'a freelance photographer', 
      'take advantage now', 
      'm good girl ', 
      'world class ad management', 
      'a trading robot', 
      ' adult Dating ', 
      'trading robot', 
      'm good girl', 
      'you could try here http', 
      'Our site http', 
      'Make money online', 
      'these guys out http', 
      'The most common form', 
      'additional resources http', 
      'financial Robot', 
      'y cunt is wet', 
      'click here for info http', 
      'financial expert in the net', 
      'tits and pussy', 
      '.seamonkey.', 'porndl',
      'the small benefit you obtain', ' my pussy ',
      'I pick up my gift', '.startupers.',
      '.elletvweb.', '.frostyelk.', ' successful crowdfunding campaigns ',
      '.pumpati.', '.qbe-medienhaus.',
      '.echinat.', '.rbertilsson.', 'escueladelcambi', 'tazalus',
      'riviello', 'coinzh', 'tygyguip', 'emdn.cl', 'tiendaskon',
      'hierbalimon', 'bodyandsoul.com', 'puertobelenn.cl', 
      'quehacerensantiago', 'keyscan.cn', 'kjsystem.net', 
      'plz-plz.com', 'allnews.elk', 'go.hinebixi', 
      'hinebixi', 'obermatsa', 
    'nanolabs', 'breweriana', 'worldnews', 'battletech', 
    'gravedanger', 'danceit', 'dkworld', 'fqxtzbiyr', 
    'cuxavyem',  'diryjyaz', 'hojagoak', 'sakelonel', 
    'suqomuaq',  'bookeat', 'blueliners07', 'bode-roesch', 
    'coronect', 'iujxnsp', 'borisvonsmercek', 'newsworld', 
    'Jewelry and gadgets', ' NFT ', 'Facebook Promotion', 
    'fannyberlin', 'collectif-hameb', '2f-2f.de', 'chronicleshardcore', 'gepekaep.com', 
    'Telegram - @Cryptaxbot', ' NFTs ', 'telegra.ph', 
    'troydwtja', 'join our social media community', 
    'trending down for some time', 'use an authority boost',
    'ELECT (CASE WHEN', '> https:', 'europeannewstoday.com', 
    'clink profile', 'hansen-studio.com', 'website authority',
    'one million messages', 'ff-breitenbrunn.de', 'blenoir-bretagne.com',
    'binomo.com', '/rb.gy/', '/u.to/', 'crypto traiding', 
    'lavish living', 'https://galxe-web3.com/', 'https://1inch-dex.com/',
    'https://metamask-wallet-web3.com/', 'Zionist', 'kill innocent ',
    'your SEO rank', 'en dating men', ' Bybit ', ' cute capybara ',
    '/cryptaxbot/', ' best darknet shop', 'https://accsmarket.net',
    'https://collyaris.com/', 'https://goo.su/', 'https://www.opendata.nhs.scot/',
    ' Monkey Digital', ' Claim Now ', 'http://xurl.es/',
    ' for article Post', 'out.carrotquest.io', ' with Patons Yarn',
    'your + price', ' the best yarn in the entire world ',
    'https://www.speed-seo.org/', 'https://internetmosque.net/',
    'https://www.unlimitedgoogle.com/', 'Mike Allford',
    ' the price ', ' Window Tint Kit ', ' CK Auto ', ' XRumer 23',
    ' Esperio', 'https://www.speedseonet.com/', '/whatapp-us/',
    'https://thegrosmimi.com/', 'out.carrotquest-mail.io',
    'https://mypeachesandcreme.com/', ' about + the price',
    ' about your the price', 'https://thelianyu.com/',
    'https://trkmad.com/', 'https://qrcd.org/', 'https://medium.com/', 
    'https://gourl.tech/', '\-game.space/',
);

chdir "/var/www/attach";

foreach my $flag (@flags)
   {
    my $ifh = IO::File->new("grep -l \'$flag\' *|");
    next if(!defined $ifh);

    while(my $line = <$ifh>)
      {
        chomp($line);
        next if(!($line =~ /^msg/));
        system("rm $line");
      }
  }
