#!/usr/bin/env perl

use warnings;
use strict;
use v5.10;
use Getopt::Long;
use Sys::Hostname qw(hostname);
use Sys::Syslog qw(:DEFAULT setlogsock);
use File::Basename;
use File::Copy qw(move);
use Proc::PID::File;
die "Already running!" if Proc::PID::File->running();

my $debug;
my $enforce;
my $revert;
my $host = hostname();

# 512kb
my $size_thresh_bytes = 512000;

GetOptions ("debug"   => \$debug,
            "size=s"  => \$size_thresh_bytes,
            "revert"  => \$revert,
            "enforce" => \$enforce);

(bless {}, __PACKAGE__)->run();
exit;

sub run {
    my $self = shift;

    my $docroots = $self->get_docroots();

    if ($revert) {
        $self->revert($docroots);
    } else {
        $self->process_htaccess($docroots);
    }

    return;
}

sub get_docroots {
    my $self = shift;

    my @docroots = qx{grep ^documentroot /var/cpanel/userdata/*/*};
    chomp (my @user_list = qx{/usr/local/sbin/gt user_list select user --format=csv-noheaders});

    my $dpaths;
    foreach my $docroot (@docroots) {
        if ($docroot =~ m/documentroot: (.*)/) {
            $dpaths->{$1}++;
        }
    }

    foreach my $user (@user_list) {
      if ( my $homedir = ( getpwnam($user) )[7]) {
        $dpaths->{$homedir}++;
      }
    }
    return $dpaths;
}

sub process_htaccess {
    my $self = shift;
    my $docroots = shift;

    my $htaccess_files = {};

    foreach my $dpath ( keys %{$docroots} ) {
        if (-f "$dpath/.htaccess") {
            my $fsize = -s "$dpath/.htaccess";
            if ($fsize >= $size_thresh_bytes) {
                $htaccess_files->{"$dpath/.htaccess"}++;
                say "$host:$dpath/.htaccess:$fsize" if $debug;
                $self->log("$dpath/.htaccess is over size threshold of $size_thresh_bytes (Found $fsize)");
            }
        }
    }

    use Data::Dumper;
    say Dumper(\$htaccess_files) if $debug;
    my $htaccess_count = keys %{$htaccess_files};
    say "DEBUG: Number of large htaccess files found: $htaccess_count" if $debug;

    # Begin Safety Net. Bail out if number of large htaccess files exceeds accepted threshold.
    my $thresh = 100;
    die "Threshold of $thresh reached! Safety net engaged" if $htaccess_count >= $thresh;

    $self->disable_htaccess($htaccess_files) if $enforce;

    return;
}

sub disable_htaccess {
    my $self = shift;
    my $htaccess_files = shift;

    foreach my $htaccess (sort keys %{$htaccess_files}) {
        if (!-f "${htaccess}_size_violation_disable_strike1") {
            $self->log("mv $htaccess ${htaccess}_size_violation_disable_strike1");
            move("$htaccess", "${htaccess}_size_violation_disable_strike1")
                or $self->log( "FAIL: mv $htaccess ${htaccess}_size_violation_disable_strike1 : $!" );
            $self->replace_htaccess($htaccess);
        }
        elsif (!-f "${htaccess}_size_violation_disable_strike2") {
            $self->log("mv $htaccess ${htaccess}_size_violation_disable_strike2");
            move("$htaccess", "${htaccess}_size_violation_disable_strike2")
                or $self->log( "FAIL: mv $htaccess ${htaccess}_size_violation_disable_strike2 : $!" );
            $self->replace_htaccess($htaccess);
        }
        elsif (!-f "${htaccess}_size_violation_disable_strike3") {
            $self->log("mv $htaccess ${htaccess}_size_violation_disable_strike3");
            $self->log( "3rd violoation: Disabling $htaccess" );
            move("$htaccess", "${htaccess}_size_violation_disable_strike3")
                or $self->log( "FAIL: mv $htaccess ${htaccess}_size_violation_disable_strike3 : $!" );
            $self->replace_htaccess($htaccess);
        }
        else {
            $self->log("unlink $htaccess");
            $self->log( "4th violation: Removing $htaccess" );
            unlink $htaccess;
            $self->replace_htaccess($htaccess);
        }
    }

    return;
}

sub replace_htaccess {
    my $self = shift;
    my $htaccess_file = shift;

    my ($uid, $gid);
    if (-f "${htaccess_file}_size_violation_disable_strike1") {
        $uid = (stat "${htaccess_file}_size_violation_disable_strike1")[4];
        $gid = (stat "${htaccess_file}_size_violation_disable_strike1")[5];
    }

    open my $fh, ">>$htaccess_file" or warn "$!";
    say $fh "### FIlE SIZE EXCEEDED $size_thresh_bytes BYTES ###";
    close $fh;

    chown($uid, $gid, "$htaccess_file") if $uid;

    return;
}

sub revert {
    my $self = shift;
    my $docroots = shift;

    say "NOTICE: Pipe to bash when ready to execute!";

    foreach my $dpath ( keys %{$docroots} ) {
        if ( -e "$dpath/.htaccess_size_violation_disable_strike1" && !-e "$dpath/.htaccess" ) {
            say "mv -fv $dpath/.htaccess_size_violation_disable_strike1 $dpath/.htaccess";
        }
    }

    return;
}

sub log {
    my $self = shift;
    my $msg  = shift;

    openlog(basename($0), "pid", "local3");
    syslog("warning", "$msg");
    closelog( );

    return;
}

__END__;

Description:
Remove large htaccess files that have potential to cause apache memory and performance issues.

Logic:
First offense  -  Rename htaccess file
Second offense -  Rename htaccess file
Third offense  -  Rename htaccess file
Fourth offense -  Delete htaccess file
