#!/usr/bin/perl

use warnings;
use strict;

use IO::Socket;	#to get IP address
use File::Find;
#use File::Path qw(make_path);
use File::Path qw(mkpath);

# IMPORTANT:
# After loading the debconf module DO NOT output anything to STDOUT
# use STDERR instead.
use Debconf::Client::ConfModule ':all';

our $IDP_CONF_BASE      = "/etc/shibboleth-identityprovider";
our $IDP_CONF_SKEL_BASE = "/usr/share/shibboleth-identityprovider/skel";

our $IDP_CONF_SKEL = "$IDP_CONF_SKEL_BASE/idp-conf";
our $CRED_BASE     = "$IDP_CONF_BASE/credentials";
our $CRT_NAME      = "$CRED_BASE/idp.crt";
our $KEY_NAME      = "$CRED_BASE/idp.key";
our $JKS_NAME      = "$CRED_BASE/idp.jks";

our $TOMCAT_SKEL = "$IDP_CONF_SKEL_BASE/tomcat-conf";
our $TOMCAT_BASE = "$IDP_CONF_BASE/tomcat-conf";

our $APACHE_SKEL = "$IDP_CONF_SKEL_BASE/apache-conf";
our $APACHE_BASE = "/etc/apache2/sites-available";

my $server_fqdn = (get('shibboleth-identityprovider/server_fqdn'))[1];
my $server_path = (get('shibboleth-identityprovider/server_path'))[1];
my $server_ip = inet_ntoa((gethostbyname($server_fqdn))[4]);
my $shib_url    = $server_path . "/shibboleth";
my $entity_id   = "https://" . $server_fqdn . $shib_url;
# create the directory to hold the credentials...
if (!-d $CRED_BASE) {
  mkpath($CRED_BASE);
}

# check whether the cert files exist
if (!-e $CRT_NAME && !-e $KEY_NAME && !-e $JKS_NAME) {
  print STDERR "Generating credentials...";
  system(
         'cert-generator', "-hostname", $server_fqdn, "-url", $shib_url, "-certfile", $CRT_NAME, "-keyfile", $KEY_NAME,
         "-keystore",      $JKS_NAME,
         "-storepass",     'changeit'
        );
  if ($? == -1) {
    print STDERR "failed to execute: $!\n";
  } elsif ($? & 127) {
    printf STDERR "child died with signal %d, %s coredump\n", ($? & 127), ($? & 128) ? 'with' : 'without';
  } elsif ($? != 0) {
    printf STDERR "child exited with value %d\n", $? >> 8;
  }
  print STDERR "done", "\n";
} else {
  print STDERR "Credentials already exist. Skipping.", "\n";
}

our %replacement;
$replacement{'IDP_ENTITY_ID'}   = $entity_id;
$replacement{'IDP_SCOPE'}       = $server_fqdn;
$replacement{'IDP_HOSTNAME'}    = $server_fqdn;
$replacement{'IDP_IP'}			= $server_ip;
$replacement{'IDP_PATH'}        = $server_path;
$replacement{'IDP_CERTIFICATE'} = "";

my $fh;
open($fh, "<", $CRT_NAME);
while (<$fh>) {
  next if (/^-----(BEGIN|END)/);
  $replacement{'IDP_CERTIFICATE'} .= $_;
}
close($fh);

print STDERR "processing idp conf...";
find(sub { copy_filter($IDP_CONF_SKEL, $IDP_CONF_BASE); }, @{ [$IDP_CONF_SKEL] });
print STDERR "done", "\n";
print STDERR "processing tomcat conf...";
find(sub { copy_filter($TOMCAT_SKEL, $TOMCAT_BASE); }, @{ [$TOMCAT_SKEL] });
print STDERR "done", "\n";
print STDERR "processing apache conf...";
find(sub { copy_filter($APACHE_SKEL, $APACHE_BASE); }, @{ [$APACHE_SKEL] });
print STDERR "done", "\n";

sub copy_filter {
  -d && return;    # ignore directories
  my ($src_base, $dst_base) = @_;
  my $src      = $File::Find::name;
  my $rel_path = File::Spec->abs2rel($src, $src_base);
  my $dst      = File::Spec->rel2abs($rel_path, $dst_base);
  #print STDERR $src, " -> ", $dst, "\n";
  my $dst_dir = (File::Spec->splitpath($dst))[1];

  if (!-d $dst_dir) {
    mkpath($dst_dir);
  }
  -e $dst && return;
  my ($in, $out);
  open($in,  "<", $src);
  open($out, ">", $dst);
  while (<$in>) {
    # remove the 8443 port from the hostname
    #s/\$:8443/\$/g;
    s{/idp/}{\$IDP_PATH\$/}g;
    s{/idp/}{\$IDP_IP\$/}g;
    s{/idp/}{\$IDP_HOSTNAME\$/}g;
    if (/\$([A-Z\_]+)\$/) {
      my $tok = $1;
      #print STDERR $tok, " => ", $replacement{$tok}, "\n";
      s/\$\Q$tok\E\$/$replacement{$tok}/g;
    }
    print $out $_;
  }
  close $in;
  close $out;
} ## end sub copy_filter

