#!/usr/bin/perl
use strict;
use File::Copy;
use Sys::Hostname;


my $ajp_port  = shift;
unless($ajp_port)
{
    $ajp_port = 9444;
}

sub update_server_xml
{
    my $server_filename = '/etc/pki-ca/server.xml';
    my $new_filename = $server_filename.'.new';


    open (INFILE, "<". $server_filename);
    open (OUTFILE, ">". $new_filename);
    while (<INFILE>) {
        print OUTFILE "$_";
        if ($_ =~  'Define an AJP 1.3 Connector on port'){
            print (OUTFILE "<Connector port=\"9447\" protocol=\"AJP/1.3\" redirectPort=\"$ajp_port\" />}\n");
        }
    }
    close (INFILE);
    close (OUTFILE);

    rename ( $new_filename,  $server_filename)
}

sub update_proxy_conf
{
    my $template_file = '/usr/share/pki/ca/conf/proxy.conf';
    my $server_filename = '/etc/pki-ca/proxy.conf';
    my $new_filename = $server_filename.'.new';


    #backup, just in case there already was afile
    copy ($server_filename, $server_filename . '.orig'  );

    copy ($template_file, $server_filename  );

    open (INFILE, "<". $server_filename);
    open (OUTFILE, ">". $new_filename);
    while (<INFILE>) {
        my $host = hostname;
        s/\[PKI_MACHINE_NAME\]/$host/;
        s/\[PKI_AJP_PORT\]/$ajp_port/;
        print OUTFILE "$_";
    }
    close (INFILE);
    close (OUTFILE);

    rename ( $new_filename,  $server_filename)
}

print "updating proxy with AJP port $ajp_port\n";

update_server_xml();
update_proxy_conf();
