#!/usr/bin/perl

# configure.pl
# 02.01.2016
#
# The proxy software, when run on a server, will use different directories,
# host names, tcp ports, etc. than the server on which this software was
# originally written.
# These things are defined in the file 'settings'.
# This script is called from the makefile. It reads the settings file and
# inserts the information in the source files.
#
#    Copyright (C) 2015-2016  Balthasar Szczepański
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

unless ($ARGV[0]) {
	print STDERR "Configfile missing.\n";
	exit 1;
}

unless (open $configfile, "<", $ARGV[0]) {
	print STDERR "Cannot open configfile\n";
	exit 2;
}

# Read the config file, line format:
# some_name = some value # some comment
while (defined(my $line = <$configfile>)) {
	$line =~ s/[\r\n]//g;
	$line =~ s/#.*$//; #comment
	if ($line =~ /^[ \t]*([a-zA-Z0-9_\-\.]+)[ \t]*=[ \t]*([^ \t](.*[^ \t])?)[ \t]*$/){
		my $name=$1;
		my $value=$2;
		$set{$name}=$value;
	}
}
close ($configfile);

# Now generate things to be inserted.

$def{'UNLOCK_LOG'}        = "use constant UNLOCK_LOG         => '".$set{'log_path'}."unlock.log';";
$def{'CURL_PATH'}         = "use constant CURL_PATH          => '".$set{'curl'}."';";
$def{'GZIP_PATH'}         = "use constant GZIP_PATH          => '".$set{'gzip'}."';";
$def{'DATA_PATH'}         = "use constant DATA_PATH          => '".$set{'data_path'}."';";
$def{'LOG_PATH'}          = "use constant LOG_PATH           => '".$set{'log_path'}."';";
$def{'TEMP_PATH'}         = "use constant TEMP_PATH          => '".$set{'tmp_path'}."';";
$def{'PASS_PATH'}         = "use constant PASS_PATH          => '".$set{'data_path'}."pass/';";
$def{'ARCH_PATH'}         = "use constant ARCH_PATH          => '".$set{'data_path'}."archive/';";
$def{'ACCESS_PATH'}       = "use constant ACCESS_PATH        => '".$set{'data_path'}."access/';";
$def{'UNLOCK_PROXY_URL'}  = "use constant UNLOCK_PROXY_URL   => 'http://".$set{'unlock_domain'}.$set{'unlock_path'}."';";
$def{'UNLOCK_PROXY_URL_S'}= "use constant UNLOCK_PROXY_URL_S => 'https://".$set{'unlock_domain'}.$set{'unlock_path'}."';";
$def{'UNLOCK_PROXY_HOST'} = "use constant UNLOCK_PROXY_HOST  => qr/".$set{'unlock_domain_regex'}."/;";
$def{'UNLOCK_PROXY_PATH'} = "use constant UNLOCK_PROXY_PATH  => qr/".$set{'unlock_path_regex'}."/;";
$def{'BLOCK_HOST'}        = "use constant BLOCK_HOST         => qr/".$set{'block_host_regex'}."/;";
$def{'BLOCK_PORT'}        = 'use constant BLOCK_PORT         => qr/^((0*'.$set{'http_proxy_port'}.')|('.$set{'https_proxy_port'}.')|('.$set{'ssl_proxy_port'}.'))$/;';
$def{'TIMEOUT_UNLOCK'}    = "use constant TIMEOUT_UNLOCK     => ".$set{'timeout_unlock'}.";";
$def{'TIMEOUT_INACT'}     = "use constant TIMEOUT_INACT      => ".$set{'timeout_inact'}.";";
$def{'TIMEOUT_ARCH'}      = "use constant TIMEOUT_ARCH       => ".$set{'timeout_arch'}.";";
$def{'LOG_SIZE_LIMIT'}    = "use constant LOG_SIZE_LIMIT     => ".$set{'log_size_limit'}.";";
$def{'LOGS_UNCOMPRESSED'} = "use constant LOGS_UNCOMPRESSED  => ".$set{'logs_uncompressed'}.";";
$def{'LOGS_TOTAL'}        = "use constant LOGS_TOTAL         => ".$set{'logs_total'}.";";
$def{'REWRITE_URL'}       = "use constant REWRITE_URL        => '".$set{'https_proxy_domain'}.":".$set{'https_proxy_port'}."';";
$def{'LIB'} = "use lib '".$set{'lib_path'}."';";


$def{'PATH'} = "\$ENV{'PATH'} = '".$set{'path'}."';";

$def{'PERL'} = "#!".$set{'perl'};

$def{'PROXY_PL'}         = '#define PROXY_PL         "'.$set{'bin_path'}.'proxy.pl"';
$def{'PROXY_PL_ERRLOG'}  = '#define PROXY_PL_ERRLOG  "'.$set{'log_path'}.'proxy-stderr.log"';
$def{'ACCESS_PL'}        = '#define ACCESS_PL        "'.$set{'bin_path'}.'access.pl"';
$def{'ACCESS_PL_ERRLOG'} = '#define ACCESS_PL_ERRLOG "'.$set{'log_path'}.'access-stderr.log"';

$def{'VIRTUAL_HOST_HTTP'} = '<VirtualHost _default_:'.$set{'http_proxy_port'}.'>';
$def{'VIRTUAL_HOST_HTTPS'}= '<VirtualHost _default_:'.$set{'https_proxy_port'}.'>';
$def{'SERVER_ADMIN'}      = "\tServerAdmin           ".$set{'server_admin'};
$def{'SERVER_NAME_HTTP'}  = "\tServerName            ".$set{'http_proxy_domain'};
$def{'SERVER_NAME_HTTPS'} = "\tServerName            ".$set{'https_proxy_domain'};
$def{'DOCUMENT_ROOT'}     = "\tDocumentRoot          ".$set{'www_path'};
$def{'CGI_ALIAS'}         = "\tScriptAliasMatch (.*) ".$set{'bin_path'}.'proxy$1';
$def{'SSL_CERT'}          = "\tSSLCertificateFile    ".$set{'ssl_cert'};
$def{'SSL_KEY'}           = "\tSSLCertificateKEYFile ".$set{'ssl_key'};
$def{'CUSTOM_LOG_HTTP'}   = "\tCustomLog             ".$set{'log_path'}.'http.log combined';
$def{'ERROR_LOG_HTTP'}    = "\tErrorLog              ".$set{'log_path'}.'http-err.log';
$def{'CUSTOM_LOG_HTTPS'}  = "\tCustomLog             ".$set{'log_path'}.'https.log combined';
$def{'ERROR_LOG_HTTPS'}   = "\tErrorLog              ".$set{'log_path'}.'https-err.log';
$def{'LISTEN_HTTP'}       = '# Listen '.$set{'http_proxy_port'};
$def{'LISTEN_HTTPS'}      = '# Listen '.$set{'https_proxy_port'};

$def{'HTTP_PORT_SSL'}     = 'http_port '.$set{'ssl_proxy_port'};
$def{'EXTERNAL_ACL'}      = 'external_acl_type unlocked-check ttl=15 negative_ttl=0 %SRC '.$set{'bin_path'}.'access';
$def{'EXTERNAL_REWRITE'}  = 'url_rewrite_program '.$set{'bin_path'}.'rewrite';
$def{'UNLOCK_DOMAIN_ACL'} = 'acl unlockdomain dstdomain '.$set{'unlock_domain'};

$def{'RM_ACCESS_CRONTAB'} = $set{'rm_access_crontab'}.' '.$set{'rm'}.' '.$set{'data_path'}.'access/*';
$def{'CLEARARCH_CRONTAB'} = $set{'cleararch_crontab'}.' '.$set{'bin_path'}.'cleararch >> '.$set{'log_path'}.'cleararch.log';
$def{'OLDLOGS_CRONTAB'}   = $set{'oldlogs_crontab'}.' '.$set{'bin_path'}.'oldlogs';


$def{'CC'} = 'CC='.$set{'gcc'};
$def{'CF'} = 'CF='.$set{'c_flags'};
$def{'PL'} = 'PL='.$set{'perl'};
$def{'MV'} = 'MV='.$set{'mv'};
$def{'CP'} = 'CM='.$set{'cp'};
$def{'RM'} = 'RM='.$set{'rm'};
$def{'OD'} = 'OD='.$set{'bin_path'};
$def{'LD'} = 'LD='.$set{'lib_path'};
$def{'CM'} = 'CM='.$set{'chmod'};


# Now go through input file, find lines to be replaced. Format:
# ###SOME_NAME;
# If found - replace.

while (defined($line = <STDIN>)) {
	$line =~ s/[\r\n]//g;
	if ($line =~ /###([a-zA-Z0-9_]+);/) {
		print "$def{$1}\n";
	}
	else {
		print "$line\n";
	}
}
