#!/usr/bin/perl
# htaccess2myapacheconf v1.1  (c) 14.5.2012 by Andreas Ley  (u) 8.10.2014
# Find all .htaccess and add appropriate <Directory> directives

use locale;
use Getopt::Std;
use File::Find;
use File::Spec::Functions;

sub usage
{
	my $image = $0;
	$image =~ s!.*/!!;
	print STDERR "Usage: $image [-v] [directory [...]]\n";
	exit(1);
}

getopts('Dhxv') or &usage;

&usage if (defined($opt_h));

if (defined($opt_v) || defined($opt_D)) {
	$|=1;
	select((select(STDERR),$|=1)[0]);
}

# Since we start sub-finds with possibly different currentdir, we can't
# expand paths at .htaccess detection time

my $pwd = $ENV{'PWD'};
my @args = $#ARGV<0 ? $pwd : map { /^\// ? $_ : catfile($pwd,$_) } @ARGV;

print STDERR "find \"",join('" "',@args),"\"\n" if ($opt_D>0);
find(\&wanted,@args);

sub wanted
{
	print STDERR "wanted: \"$_\" in $File::Find::dir\n" if ($opt_D>0);
	if (-d $_ && -f catfile($_,'.allowoverride')) {
		my $path = $File::Find::dir;
		print STDERR "allowoverride: \"$path\"\n" if ($opt_D>0);
		1 while ($path =~ s!/[^/]+/\.\./!/!);
		push(@allowoverride,$path);
		print "\n","#"x80,"\n#\n# $File::Find::name\n#\n\n" if ($opt_v);
		print "<Directory $path>\n";
		print "	AllowOverride	All\n";
		print "</Directory>\n";
	}
	elsif ($_ eq '.htaccess' && -f $_ && -s $_) {
		my $path = $File::Find::dir;
		print STDERR "htaccess: \"$path\"\n" if ($opt_D>0);
		1 while ($path =~ s!/[^/]+/\.\./!/!);
		if (!grep($_ eq $path || $_.'/' eq substr($path,$[,length($_)+1),@allowoverride)) {
			print "\n","#"x80,"\n#\n# $File::Find::name\n#\n\n" if ($opt_v);
			print "<Directory $path>\n";
			open(HTACCESS,$_) or die "Can't read $File::Find::name: $!\n";
			while (<HTACCESS>) {
				chomp;
				print $_,"\n";
			}
			close(HTACCESS);
			print "</Directory>\n";
		}
	}
	elsif (-l $_ && -d $_.'/') {
		print STDERR "find \"$File::Find::name/\"\n" if ($opt_D>0);
		find(\&wanted,$File::Find::name.'/');
	}
}
