#!/usr/bin/perl

use strict;

my $prefix = "/etc/caterva/squid/squid.conf";

my $out;
open(out, ">$prefix/00-prefix") || die "Unable to open the output file";
my $has_auth_param = 0;
while (<STDIN>) {
	print out;
	if (/^##*auth_param/) {
		$has_auth_param = 1;
		while (<STDIN>) {
			if (/^#/) {
				print out;
			} elsif (/^(auth_param|acl)/) {
				next;
			} else {
				last;
			}
		}
		last;
	}
}
if ($has_auth_param == 0) {
	close(out);
	open(out, ">$prefix/00-prefix") || die "Unable to open the output file";
}
close(out);

open(out, ">$prefix/02-acl-prefix") || die "Unable to open the output file";
unless (/^acl\s+(SSL_ports|Safe_ports)/) {
	print out;
	while (<STDIN>) {
		if (/^acl\s+(SSL_ports|Safe_ports)/) {
			last;
		}
		print out;
	}
	close(out);
}
while (<STDIN>) {
	if (! /^acl\s+(SSL_ports|Safe_ports)/) {
		last;
	}
}

open(out, ">$prefix/04-base-access") || die "Unable to open the output file";
print out;
while (<STDIN>) {
	if (/^acl\s+(SSL_ports|Safe_ports)/) {
		print out "#$_";
		next;
	}
	print out;
	if (/^http_access\s+[a-z]+\s+manager/) {
		while (<STDIN>) {
			if (/^http_access\s+[a-z]+\s+manager/) {
				print out;
			} else {
				last;
			}
		}
		last;
	}
}
close(out);

open(out, ">$prefix/07-to-local-host") || die "Unable to open the output file";
print out if /^\s*$/ || /^##*/;
while (<STDIN>) {
	if (/^#*http_access\s+deny\s+to_localhost/) {
		print out;
		last;
	} elsif (/^\s*$/ || /^##*/) {
		print out;
	} else {
		close(out);
		open(out, ">$prefix/07-to-local-host") || die "Unable to open the output file";
	}
}
close(out);

open(out, ">$prefix/20-deny-all") || die "Unable to open the output file";
my $has_deny_all = 0;
while (<STDIN>) {
	if (/^http_access\s+deny\s+all/) {
		print out;
        $has_deny_all = 1;
		last;
	} elsif (/^##*/) {
		print out;
	} elsif (/^\s*$/) {
		close(out);
		open(out, ">$prefix/20-deny-all") || die "Unable to open the output file";
	} else {
		close(out);
		open(out, ">$prefix/20-deny-all") || die "Unable to open the output file";
	}
}
if ($has_deny_all == 0) {
    print out "# Finally deny all other access to this proxy\n";
    print out "http_access deny all\n";
}
close(out);

open(out, ">$prefix/30-access-tail") || die "Unable to open the output file";
while (<STDIN>) {
	if (/^acl\s+(SSL_ports|Safe_ports)/) {
		print out "#$_";
		next;
	}
	if (/^(http_access|acl|external_acl_type)/) {
		print out "#$_";
		next;
	}
	if (/^##*http_port/) {
		print out;
		last;
	} elsif (/^http_port/) {
		print out "#$_";
		last;
	}
	print out;
}
close(out);

open(out, ">$prefix/90-tail") || die "Unable to open the output file";
while (<STDIN>) {
	if (/^acl\s+(SSL_ports|Safe_ports)/) {
		print out "#$_";
		next;
	}
	if (/^http_access/) {
		print out "#$_";
		next;
	}
	if (/^http_port/) {
		next;
	} else {
		print out;
	}
}
close(out);

