#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - whmcs_configure_htaccess                  Copyright 2018 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited
package scripts::whmcs_configure_htaccess;

use strict;
use warnings;

use Getopt::Long                 ();
use Pod::Usage                   ();
use Cpanel::HttpUtils::Htaccess  ();
use Cpanel::FileUtils::TouchFile ();

=head1 DESCRIPTION

This script makes the necessary .htaccess change to prevent files under certain
directories from being accessible via the web.

=head1 USAGE

whmcs_configure_htaccess --dir={install directory}

Where:

=over

=item * --dir={string} - the install directory for whmcs on the file system.

=back

=cut

exit( __PACKAGE__->run(@ARGV) ) if !caller;

=head1 FUNCTIONS

=head2 run(dir => {String})

Modulino for the whmcs_configure_htaccess program.

=head3 ARGUMENTS

HASH with the following structure:

=over

=item dir

String - The location where whmcs php files are located for the specific install. Required.

=back

=head3 RETURNS

1 if successful

=head3 THROWS

=over

=item * When you do not pass in the required arguments.

=item * When the needed change could not be made to the .htaccess file.

=back

=cut

sub run {
    my ( $self, @args ) = @_;
    my ( $help, $man, $dir, $verbose, $debug ) = ( 0, 0, '', '', 0, 0 );

    Getopt::Long::GetOptionsFromArray(
        \@args,
        'help|?'    => \$help,
        'man'       => \$man,
        'dir=s'     => \$dir,
        'verbose|v' => \$verbose,
        'debug'     => \$debug,
    ) or Pod::Usage::pod2usage(2);
    Pod::Usage::pod2usage(1) if $help;
    Pod::Usage::pod2usage( -exitval => 0, -verbose => 2 ) if $man;

    if ( !$dir ) {
        die 'You must pass the install directory parameter: --dir';
    }

    _fix_htaccess($dir);

    if ($verbose) {
        print "WHMCS .htaccess configuration updated\n";
    }

    return 0;
}

sub _fix_htaccess {
    my ($dir) = @_;

    if ( !-d $dir ) {
        die "The directory “$dir” does not exist.\n";
    }

    my @subdirs = map { "$dir/$_" } qw(attachments downloads templates_c);

    for my $subdir (@subdirs) {
        mkdir $subdir if !-d $subdir;
        my $htaccess_file = $subdir . '/.htaccess';
        Cpanel::FileUtils::TouchFile::touchfile($htaccess_file) if !-f $htaccess_file;

        my $htaccess_trans = Cpanel::HttpUtils::Htaccess::open_htaccess_rw($subdir);
        my $htaccess_sr    = $htaccess_trans->get_data();
        $$htaccess_sr .= <<EOF;

# Added by $0
Order Allow,Deny
Deny from all
EOF
        $htaccess_trans->save_and_close_or_die();
    }

    return;
}

1;
