#!/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 JSON::XS;
use File::Slurp qw(write_file read_file);
use POSIX qw(setuid setgid);
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 $user_docroots = $self->get_user_docroots();

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

    return;
}

sub get_user_docroots {
    my $user_docroots = {};
    my $json_path = '/etc/userdatadomains.json';
    return $user_docroots unless -f $json_path;

    my $json_text = eval { read_file($json_path) };
    return $user_docroots if $@ || !defined $json_text;

    my $data = eval { decode_json($json_text) };
    return $user_docroots if $@;

    while (my ($domain, $entry) = each %{$data}) {
        next unless ref($entry) eq 'ARRAY';
        my ($user, undef, undef, undef, $docroot) = @{$entry};
        next unless $user && $docroot;

        my @pw = getpwnam($user);
        next unless @pw;

        $user_docroots->{$user} ||= { uid => $pw[2], gid => $pw[3], docroots => {} };
        $user_docroots->{$user}->{docroots}->{$docroot} = 1;
    }
    return $user_docroots;
}

sub process_htaccess {
    my ($self, $user_docroots) = @_;
    my $htaccess_files = {};

    foreach my $user (sort keys %$user_docroots) {
        my $info = $user_docroots->{$user};
        my ($uid, $gid) = ($info->{uid}, $info->{gid});

        foreach my $dpath (keys %{$info->{docroots}}) {
            my $htaccess = "$dpath/.htaccess";
            my $pid = fork();
            die "Fork failed: $!" unless defined $pid;

            if ($pid == 0) {
                setgid($gid) or exit 1;
                setuid($uid) or exit 1;
                if (-f $htaccess && !-l $htaccess && -s $htaccess >= $size_thresh_bytes) {
                    my $fsize = -s $htaccess;
                    say "DEBUG CHILD: user=$user, uid=$<, euid=$>" if $debug;
                    say "$host:$htaccess:$fsize" if $debug;
                    exit 0;
                }
                exit 1;
            }

            waitpid($pid, 0);
            if ($? == 0) {
                $htaccess_files->{$htaccess} = { uid => $uid, gid => $gid };
                $self->log("$htaccess is over size threshold");
            }
        }
    }

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

    die "Threshold reached! Safety net engaged" if $count >= 100;

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

    return;
}

sub disable_htaccess {
    my ($self, $htaccess_files) = @_;

    foreach my $htaccess (sort keys %$htaccess_files) {
        my $info = $htaccess_files->{$htaccess};
        my ($uid, $gid) = ($info->{uid}, $info->{gid});

        $self->log("Processing violation for $htaccess");
        my $pid = fork();
        die "Fork failed: $!" unless defined $pid;

        if ($pid == 0) {
            setgid($gid) or exit 1;
            setuid($uid) or exit 1;

            exit 0 if -l $htaccess;

            my $strike = '';
            if    (!-f "${htaccess}_size_violation_disable_strike1") { $strike = 'strike1'; }
            elsif (!-f "${htaccess}_size_violation_disable_strike2") { $strike = 'strike2'; }
            elsif (!-f "${htaccess}_size_violation_disable_strike3") { $strike = 'strike3'; }

            if ($strike) {
                move($htaccess, "${htaccess}_size_violation_disable_$strike");
            } else {
                unlink $htaccess;
            }
            $self->replace_htaccess($htaccess);
            exit 0;
        }
        waitpid($pid, 0);
    }

    return;
}

sub replace_htaccess {
    my ($self, $htaccess) = @_;
    my $notice = "### FILE SIZE EXCEEDED $size_thresh_bytes BYTES ###\n";

    eval { write_file($htaccess, { atomic => 1 }, $notice) };
    if ($@) {
        $self->log("CRITICAL: Atomic write failed for $htaccess: $@");
    }

    return;
}

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

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

    foreach my $user (keys %{$user_docroots}) {
        my $info = $user_docroots->{$user};
        foreach my $dpath (keys %{$info->{docroots}}) {
            my $htaccess_path = "$dpath/.htaccess";
            if ( -e "${htaccess_path}_size_violation_disable_strike1" && !-e $htaccess_path ) {
                say "mv -fv ${htaccess_path}_size_violation_disable_strike1 $htaccess_path";
            }
        }
    }

    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. Drops privileges per user during inspection.

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