#!@l_prefix@/bin/perl

# (c) 2004 Steffen Hansen <steffen@klaralvdalens-datakonsult.se>
# (c) 2003,2004 Tassilo Erlewein <tassilo.erlewein@erfrakon.de>
# (c) 2003-2005 Martin Konold <martin.konold@erfrakon.de>
# (c) 2003 Achim Frank <achim.frank@erfrakon.de>
#
# This program is Free Software under the GNU General Public License (>=v2).
# Read the file COPYING that comes with this packages for details.

# kolab_bootstrap Version 0.93

use strict;
use vars qw($opt_b $opt_f);

use URI;
use Socket;
use IO::File;
use IO::Select;
use Net::LDAP;
use Net::LDAP::Entry;
use Net::Netmask;
use File::Copy;
use Getopt::Std;
use Sys::Hostname;
use Term::ReadKey;
use Time::Local;
use Time::localtime;

my $kolab_prefix = "@l_prefix@";
my $kolab_config = $kolab_prefix."/etc/kolab/kolab.conf";
my %kolab_config;

##### Utility Functions

# Shell double-quote a string
# Borrored from Sysadm::Install
sub qquote {
  my($str, $metas) = @_;
  $str =~ s/([\\"])/\\$1/g;
  if(defined $metas) {
    $metas = '!$`' if $metas eq ":shell";
    $metas =~ s/\]/\\]/g;
    $str =~ s/([$metas])/\\$1/g;
  }
  return "\"$str\"";
}

# Try to get fqdn
sub myhostname {
  my $host = '';
  if( open( HOSTNAME, '/etc/HOSTNAME' ) ) {
    $host = <HOSTNAME>;
    chomp $host;
    close( HOSTNAME );
  }
  if( open( HOSTNAME, '/etc/hostname' ) ) {
    $host = <HOSTNAME>;
    chomp $host;
    close( HOSTNAME );
  }
  if( $host eq '' ) {
    $host = `hostname`;
  }
  return $host;
}

# Connect to host,port and return 1 on success
sub tryConnect {
  my $host  = shift;
  my $port    = shift;
  if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') }
  die "No port" unless $port;
  my $iaddr   = inet_aton($host)               || die "no host: $host";
  my $paddr   = sockaddr_in($port, $iaddr);
  my $proto   = getprotobyname('tcp');
  socket(SOCK, PF_INET, SOCK_STREAM, $proto)  || die "socket: $!";
  my $retval = connect(SOCK, $paddr) || 0;
  close( SOCK );
  return $retval;
}

# Check for running service
sub checkPort {
  my $name = shift; # Name of the service e.g. webserver
  my $port = shift; # tcp Port of the named service
  print ("Check for running $name on port $port\n");
  if (tryConnect("localhost",$port) == 1) {
    print ("Error: Found $name running on Port $port\n");
    print ("Check your installation!\n");
    print ("You must stop the service $name before running Kolab\n");
    print ("You may try to execute \"$kolab_prefix/bin/openpkg rc all stop\" initially\n");
    exit 1;
  }
}

# Hash a password
sub hashPassword {
  my $pw = shift;
  my $hashcmd = $kolab_prefix."/sbin/slappasswd -s ".qquote($pw,":shell");
  (my $hashpw = `$hashcmd`) or die $@;
  chomp($hashpw);
  return $hashpw;
}

# Ask the user a question
sub getUserInput {
  my $text = shift;
  my $default = shift;
  my @values = @_;

  if( $default ) {
        $text = "$text [$default]";
  }
  if( @values ) {
        $text = "$text (".join('/', @values)."): ";
  } else {
        $text = "$text: ";
  }
AGAIN:
  print $text;
  my $tmp = ReadLine;
  chomp $tmp;
  if( $default && $tmp eq '' ) { $tmp = $default; }
  if( @values ) {
    foreach( @values ) { return $tmp if( $tmp eq $_ ); }
    goto AGAIN;
  }
  return $tmp;
}

# Like system() but echo the line before executing
sub kolab_system {
  my $arg = shift;
  print "$arg\n";
  system( $arg ) == 0
    or die "system $arg failed: $?";
};

# Usable chown
sub kolab_chown {
    my $u = shift;
    my $g = shift;
    my $uid = getpwnam($u);
    my $gid = getgrnam($g);
    while( my $file = shift ) {
	chown $uid,$gid,$file;
    }
}

# Fetch entry from ldap server or create new entry of none exist
sub newOrExistingLDAPEntry {
  my $ldap = shift;
  my $dn = shift;

  my $mesg = $ldap->search( base => $dn, scope => 'exact', filter => '(objectClass=*)' );
  if( $mesg && $mesg->count() > 0 ) {
    return $mesg->entry(0);
  } else {
    return Net::LDAP::Entry->new;
  }
}

sub newkolabgroupofnames {
  my $ldap = shift;
  my $basedn = shift;
  my $cn = shift;

  if( scalar(@_) < 1 ) {
    warn "kolabgroupofnames must contain at least one member";
  }

  my $ldapobject = newOrExistingLDAPEntry($ldap,"cn=$cn,$basedn");
  $ldapobject->replace('cn' => $cn, 'objectclass' => ['top','kolabgroupofnames'],
		       'member' => @_);
  $ldapobject->dn("cn=$cn,$basedn");
  my $mesg = $ldapobject->update($ldap);
  $mesg && $mesg->code && warn "failed to write entry: ", $mesg->error;
  return $ldapobject;
}

print "\nKOLAB BOOTSTRAP\n\n";

# Check for already running services preventing proper operation of kolab_bootstrap and Kolab
checkPort("webserver",80);    # http
checkPort("webserver",443);   # https
checkPort("imap server",143); # imap
checkPort("imap server",220); # 
checkPort("imap server",585);
checkPort("imap server",993);
checkPort("pop3 server",109);
checkPort("pop3 server",110);  # pop3
checkPort("pop3 server",473);
checkPort("pop3 server",995);
checkPort("smtp server",25);   # smtp
checkPort("smtp server",465);
checkPort("ftp server",21);
checkPort("Amavis Virus Scanner Interface",10024);
checkPort("Kolab daemon",9999);
checkPort("OpenLDAP server",636);
checkPort("OpenLDAP server",389);
checkPort("Sieve server",2000);

print ("Excellent all required Ports are available!\n");

system($kolab_prefix."/sbin/slapcat >/dev/null 2>&1");
if ($?==0) {
  print ("\nFound existing configuration\n");
  print "\nBootstrapping Kolab will overwrite old configuration\n";
  my $tmp = getUserInput( "\nContinue", "n", "y", "n" );
  if( (lc $tmp eq 'n') || ($tmp eq '')  ) {
    print "Bootstrapping aborted - not creating new configuration\n";
    exit 0;
  }
  print "Creating backup of old configuration (LDAP, kolab.conf and certificates\n";
  my $epochseconds = timelocal(gmtime);
  my $backupdir=$kolab_prefix."/etc/kolab/backup".$epochseconds;
  mkdir($backupdir,0700) || die "cannot mkdir : $!";
  print "creating backup of LDAP repository\n";
  system("cp -pRP ".$kolab_prefix."/var/openldap/openldap-data/ ".$backupdir."/openldap-data");
  system("rm -f ".$kolab_prefix."/var/openldap/openldap-data/*");
  print "creating backup of CA data\n";
  system("mv ".$kolab_prefix."/etc/kolab/ca ".$backupdir);
  system("mv ".$kolab_prefix."/etc/kolab/*.pem ".$backupdir);
  system("mv $kolab_config $backupdir");
  print "Cleaning up LDAP\n";
  system("rm -f ".$kolab_prefix."/var/openldap/openldap-data/*");
} else {
  print "LDAP repository is empty - assuming fresh install\n";
}


# fetch fresh template
copy($kolab_prefix."/etc/kolab/templates/kolab.conf.template", $kolab_config);

my $fd = IO::File->new($kolab_config, "r")
   || die "could not open $kolab_config";
foreach (<$fd>) {
   if (/(.*) : (.*)/) {
      $kolab_config{$1} = $2;
   }
}
undef $fd;
my $fqdnhostname = $kolab_config{'fqdnhostname'} || die "could not read fqdnhostname from $kolab_config";
my $is_master = $kolab_config{'is_master'} || "true";
my $bind_dn = $kolab_config{'bind_dn'} || die "could not read bind_dn from $kolab_config";
my $bind_pw = $kolab_config{'bind_pw'} || die "could not read bind_pw from $kolab_config";
my $bind_pw_hash = $kolab_config{'bind_pw_hash'} || hashPassword( $bind_pw );
my $ldap_uri = $kolab_config{'ldap_uri'} || die "could not read ldap_uri from $kolab_config";
my $base_dn = $kolab_config{'base_dn'} || die "could not read base_dn from $kolab_config";
my $php_dn = $kolab_config{'php_dn'} || die "could not read php_dn from $kolab_config";
my $php_pw = $kolab_config{'php_pw'} || die "could not read php_pw from $kolab_config";
my $calendar_dn = $kolab_config{'calendar_dn'};
my $calendar_pw = $kolab_config{'calendar_pw'};
my @kolabhosts;

if (!$bind_dn || !$bind_pw || !$ldap_uri || !$base_dn) {
   print "Please check $kolab_config (seems to be incomplete)\n";
   die "and run kolab_bootstrap afterwards, manually";
}
my $fqdn;
if( $fqdnhostname =~ /\@\@\@/ ) {
  $fqdn = myhostname;
} else {
  $fqdn = $fqdnhostname;
}
chomp($fqdn);

$fqdn = getUserInput("Please enter Hostname including Domain Name (e.g. thishost.domain.tld)", $fqdn);
print "Proceeding with Hostname $fqdn\n";

my $tmp;
if( $is_master eq "false" ) {
  $tmp = "2";
} else {
  $tmp = "1";
}

my $tmp2 = getUserInput( "Do you want to set up (1) a master Kolab server or (2) a slave",
			 $tmp, "1", "2");
if ( $tmp2 eq "2" ) {
  $is_master = "false";
  print "Proceeding with slave server setup\n\n";
} else {
  $is_master = "true";
  print "Proceeding with master server setup\n\n";
}

if ( $is_master eq "true" ) {
  ##### Master server setup
  getopt('f');

  (my $dummy, my $domain) = split(/\./, $fqdn, 2);
  if (!$domain) {
    $domain = $fqdn;
  }

  $domain = getUserInput("Please enter your Maildomain - if you do not know your mail domain use the fqdn from above", $domain);
  print "proceeding with Maildomain $domain\n";
  print "Kolab primary email addresses will be of the type user\@$domain \n";
  

  if ( $opt_f || $base_dn =~ /\@\@\@/ || $bind_dn =~ /\@\@\@/ || $bind_pw =~ /\@\@\@/ ) {
    print "Generating default configuration:\n";
    if ($base_dn =~ /\@\@\@/) {
      $base_dn = "";
      foreach my $dc ((split(/\./,$domain))) {
        $base_dn .= "dc=$dc,";
      }
      chop $base_dn;
      print " base_dn : $base_dn\n";
    }
    if ($bind_dn =~ /\@\@\@/) {
      $bind_dn =~ s/\@\@\@kolab_basedn\@\@\@/$base_dn/g;
      print " bind_dn : $bind_dn\n";
    }
    if ($bind_pw =~ /\@\@\@/) {
      $bind_pw = `$kolab_prefix/bin/openssl rand -base64 12`;
      chomp $bind_pw;
      $bind_pw = getUserInput("Please choose a manager password", $bind_pw);
      print " bind_pw : $bind_pw\n";
      $bind_pw_hash = hashPassword($bind_pw);
    }

    # Generate passwords
    if ($php_dn =~ /\@\@\@/) {
      $php_dn =~ s/\@\@\@kolab_basedn\@\@\@/$base_dn/g;
    }
    if ($php_pw =~ /\@\@\@/) {
      $php_pw = `$kolab_prefix/bin/openssl rand -base64 30`;
      chomp $php_pw;
    }
    if ($calendar_dn =~ /\@\@\@/) {
      $calendar_dn =~ s/\@\@\@kolab_basedn\@\@\@/$base_dn/g;
      chomp $calendar_dn;
    }
    if ($calendar_pw =~ /\@\@\@/) {
      $calendar_pw = `$kolab_prefix/bin/openssl rand -base64 30`;
      chomp $calendar_pw;
    }

    $fd = IO::File->new($kolab_config, "w+") || die "could not open $kolab_config";
    print $fd "fqdnhostname : $fqdn\n";
    print $fd "is_master : $is_master\n";
    print $fd "base_dn : $base_dn\n";
    print $fd "bind_dn : $bind_dn\n";
    print $fd "bind_pw : $bind_pw\n";
    print $fd "bind_pw_hash : $bind_pw_hash\n";
    print $fd "ldap_uri : $ldap_uri\n";
    print $fd "ldap_master_uri : $ldap_uri\n";
    print $fd "php_dn : $php_dn\n";
    print $fd "php_pw : $php_pw\n";
    print $fd "calendar_dn : $calendar_dn\n";
    print $fd "calendar_pw : $calendar_pw\n";
    undef $fd;
    print "done modifying $kolab_config\n\n";
    chmod 0600, $kolab_config;
    kolab_chown "@l_musr@","@l_mgrp@",$kolab_config;
    print "IMPORTANT NOTE:\n";
    print "use login=manager and passwd=$bind_pw when you log into the webinterface!\n\n";
  }

  # Set up slapd to replicate to slave server's kolabds
  @kolabhosts = ( $fqdn );
  while(1) {
    my $tmp = getUserInput("Enter fully qualified hostname of slave kolab server e.g. thishost.domain.tld [empty when done]");
    if( $tmp ) {
      push @kolabhosts, $tmp;
      #$cfg .= "replica host=$tmp\n";
      #$cfg .= "  binddn=\"cn=replicator\"\n";
      #$cfg .= "  bindmethod=simple credentials=secret\n\n";
    } else {
      last;
    }
  };

  my $confname = "$kolab_prefix/etc/sasl/apps/smtpd.conf";
  copy("$kolab_prefix/etc/kolab/templates/smtpd.conf.template", $confname) || die "could not write to $confname";

  getopts('b');

  if ($opt_b) {
    print "prepare LDAP database...\n";
    if ($ldap_uri =~ /127\.0\.0\.1/ || $ldap_uri =~ /localhost/) {
#      This cannot happen anymore
#      print "stop running slapd (if any)\n";
#      system("$kolab_prefix/bin/openpkg rc openldap stop");
#      sleep 5;

      # Make sure that no rogue daemons are running
      tryConnect( '127.0.0.1', 389 ) && die "A process is already listening to port 389 (ldap)\n"
        ."Please stop any running ldap server and bootstrap again\n";
      tryConnect( '127.0.0.1', 9999 ) && die "A process is already listening to port 9999 (kolabd)\n"
        ."Please stop any running kolabd and bootstrap again\n";
      if( `ps aux|grep slurpd|grep -v grep` ) {
        print "Error: Detected running slurpd processes.\n";
        print "Please make sure the OpenLDAP server is stopped properly!\n";
        exit 1;
      }

      # Creating slapd.conf from template
      my $tmpl = IO::File->new("$kolab_prefix/etc/kolab/templates/slapd.conf.template", "r") || die "could not read $kolab_prefix/etc/kolab/templates/slapd.conf.template";
      my $slpd = IO::File->new("$kolab_prefix/etc/openldap/slapd.conf","w+") || die "could not write to $kolab_prefix/etc/openldap/slapd.conf";
      chmod (0640,"$kolab_prefix/etc/openldap/slapd.conf");
      foreach (<$tmpl>) {
        s/\@\@\@base_dn\@\@\@/$base_dn/g;
        s/\@\@\@bind_dn\@\@\@/$bind_dn/g;
        s/\@\@\@bind_pw_hash\@\@\@/$bind_pw/g;
        s/TLSCertificate/\#TLSCertificate/g;
        print $slpd $_;
      }
      undef $slpd;
      undef $tmpl;

      $confname = "$kolab_prefix/etc/openldap/slapd.replicas";
      copy( "$kolab_prefix/etc/kolab/templates/slapd.replicas.template", $confname ) || die "Could not write $confname";
      chmod (0640,$confname );
      # now we must startup slapd
      print "temporarily starting slapd\n";
      $ldap_uri = "ldap://127.0.0.1:389/";
      (system("$kolab_prefix/libexec/openldap/slapd -h ldap://127.0.0.1:389/ -f $kolab_prefix/etc/openldap/slapd.conf") == 0 ) || die( "Could not start temporary slapd" );
      print ("Waiting for OpenLDAP to start\n");
      sleep 10;

    }

    my $ldapuri = URI->new($ldap_uri) || die "error: could not parse given uri";
    my $ldap = Net::LDAP->new($ldap_uri, verify => 'none' ) || die "could not connect ldap server $ldap_uri";
    if ($ldap) {
      $ldap->bind($bind_dn, password=> $bind_pw) || die "could not bind to ldap server $ldap_uri";
      my $mesg = $ldap->search(base=> "$base_dn", scope=> 'exact', filter=> "(objectclass=*)");
      if ($mesg && $mesg->count != 1) {
        print "no $base_dn object found, creating one\n";
        my $dccomp = (split(/\./,$domain))[0];
        chomp $dccomp;
        $mesg = $ldap->add( $base_dn, attr=> [dc=> $dccomp, 'objectclass'=> ['top', 'domain'] ]);
      }
      $mesg && $mesg->code && warn "failed to write basedn entry : ", $mesg->error;
      my $ldapobject = newOrExistingLDAPEntry( $ldap, "k=kolab,$base_dn" );

      # create kolab config object
      my $mynetworkinterfaces = "127.0.0.0/8";
      print "mynetworkinterfaces: ".$mynetworkinterfaces."\n";

      $ldapobject->replace(
        'k' => 'kolab',
        'kolabhost' => \@kolabhosts,
        'postfix-mydomain' => $domain,
        #'postfix-relaydomains' => "",
        'postfix-mydestination' => "\$mydomain",
        'postfix-mynetworks' => $mynetworkinterfaces,
        #'postfix-relayhost' => "",
        #'postfix-transport' => "",
        'postfix-enable-virus-scan' => "TRUE",
        'cyrus-autocreatequota' => 100000,
        'cyrus-quotawarn' => 80,
        'cyrus-admins' => "manager",
        'cyrus-imap' => "TRUE",
        'cyrus-pop3' => "FALSE",
        'cyrus-imaps' => "TRUE",
        'cyrus-pop3s' => "TRUE",
        'cyrus-sieve' => "TRUE",
        'apache-http' => "FALSE",
        'apache-allow-unauthenticated-fb' => "FALSE",
        'proftpd-ftp' => "FALSE",
        #'proftpd-defaultquota' => 100000,
        #'proftpd-userPassword' => "freebusy",
        'uid' => "freebusy",
        'userPassword' => "freebusy",
        'objectclass' => ['top', 'kolab' ] );
      # Get rid of fqdnhostname, it will cause pain and suffering...
      #$ldapobject->delete( 'fqdnhostname' );
      $ldapobject->dn("k=kolab,$base_dn");
      $mesg = $ldapobject->update($ldap);
      $mesg && $mesg->code && warn "failed to write entry: ", $mesg->error;
      undef $ldapobject;

      # create internal user topnode
      $ldapobject = newOrExistingLDAPEntry( $ldap, "cn=internal,$base_dn" );
      $ldapobject->replace('cn' => 'internal', 'objectclass' => ['top','kolabnamedobject']);
      $ldapobject->dn("cn=internal,$base_dn");
      $mesg = $ldapobject->update($ldap);
      $mesg && $mesg->code && warn "failed to write entry: ", $mesg->error;
      undef $ldapobject;

      # create external user topnode
      $ldapobject = newOrExistingLDAPEntry( $ldap, "cn=external,$base_dn" );
      $ldapobject->replace('cn' => 'external', 'objectclass' => ['top','kolabnamedobject']);
      $ldapobject->dn("cn=external,$base_dn");
      $mesg = $ldapobject->update($ldap);
      $mesg && $mesg->code && warn "failed to write entry: ", $mesg->error;
      undef $ldapobject;

      # create groups user topnode
      $ldapobject = newOrExistingLDAPEntry( $ldap, "cn=groups,$base_dn" );
      $ldapobject->replace('cn' => 'groups', 'objectclass' => ['top','kolabnamedobject']);
      $ldapobject->dn("cn=groups,$base_dn");
      $mesg = $ldapobject->update($ldap);
      $mesg && $mesg->code && warn "failed to write entry: ", $mesg->error;
      undef $ldapobject;

      # create resources user topnode
      $ldapobject = newOrExistingLDAPEntry( $ldap, "cn=resources,$base_dn" );
      $ldapobject->replace('cn' => 'resources', 'objectclass' => ['top','kolabnamedobject']);
      $ldapobject->dn("cn=resources,$base_dn");
      $mesg = $ldapobject->update($ldap);
      $mesg && $mesg->code && warn "failed to write entry: ", $mesg->error;
      undef $ldapobject;

      # create admin group
      newkolabgroupofnames( $ldap, "cn=internal,$base_dn", 'admin', $bind_dn );

      # create manager user
      $ldapobject = newOrExistingLDAPEntry( $ldap, $bind_dn );
      $ldapobject->replace('cn' => 'manager', 'sn' => 'n/a', 'uid' => 'manager',
                           'userPassword' => $bind_pw_hash, 'objectclass' => ['top','inetorgperson','kolabinetorgperson']);
      $ldapobject->dn($bind_dn);
      $mesg = $ldapobject->update($ldap);
      $mesg && $mesg->code && warn "failed to write entry: ", $mesg->error;
      undef $ldapobject;

      # create php read-only user
      $ldapobject = newOrExistingLDAPEntry( $ldap, "cn=nobody,cn=internal,$base_dn" );
      $ldapobject->replace('cn' => 'nobody', 'sn' => 'n/a n/a', 'uid' => 'nobody',
                           'userPassword' => hashPassword($php_pw), 
			   'objectclass' => ['top','inetorgperson','kolabinetorgperson']);
      $ldapobject->dn("cn=nobody,cn=internal,$base_dn");
      $mesg = $ldapobject->update($ldap);
      $mesg && $mesg->code && warn "failed to write entry: ", $mesg->error;
      undef $ldapobject;

      # create calendar user
      $ldapobject = newOrExistingLDAPEntry( $ldap, "cn=calendar,cn=internal,$base_dn" );
      $ldapobject->replace('cn' => 'calendar', 'sn' => 'n/a n/a', 'uid' => 'calendar@'.$domain,
                           'userPassword' => hashPassword($calendar_pw), 
			   'objectclass' => ['top','inetorgperson','kolabinetorgperson']);
      $ldapobject->dn("cn=calendar,cn=internal,$base_dn");
      $mesg = $ldapobject->update($ldap);
      $mesg && $mesg->code && warn "failed to write entry: ", $mesg->error;
      undef $ldapobject;

      # create mainainter group
      newkolabgroupofnames( $ldap, "cn=internal,$base_dn", 'maintainer', $bind_dn );

      $ldap->unbind;
   }

   print "LDAP setup finished\n\n";

   print "Create initial config files for postfix, apache, proftpd, cyrus imap, saslauthd\n";

   my $cfg;
   open(FH, "<$kolab_prefix/etc/rc.conf") || die;
   $cfg .= $_ while (<FH>);
   close(FH);

   $cfg =~ s/\n((openldap_url|sasl_authmech)\S*=[^\n]*)/#$1\n/sg;
   $cfg .= "openldap_url=\"ldap:// ldaps://\"\nsasl_authmech=\"ldap\"\n";

   open(FH, ">$kolab_prefix/etc/rc.conf") || die;
   print FH $cfg;
   close(FH);
   undef $cfg;

   #print " running $kolab_prefix/etc/kolab/kolab -v -o -l$ldap_uri\n";
   print "running $kolab_prefix/sbin/kolabconf -n\n";

   #system("$kolab_prefix/etc/kolab/kolab -v -o -l$ldap_uri");
   system("$kolab_prefix/sbin/kolabconf -n");

   if ($ldap_uri =~ /127\.0\.0\.1/ || $ldap_uri =~ /localhost/) {
      print "\nkill temporary slapd\n\n";
      system("$kolab_prefix/etc/rc openldap stop");
      sleep 5;
      system("killall -9 slapd >/dev/null 2>&1");
   }
  }

  # Create key-pair for resource password encryption 
  # if they dont exist already
  my $pubreskey = "$kolab_prefix/etc/kolab/res_pub.pem";
  my $privreskey = "$kolab_prefix/etc/kolab/res_priv.pem";
  if( ! -e $pubreskey || ! -e $privreskey ) {
    my $oldmask = umask 0077;
    #print "Creating DSA keypair for resource password encryption\n";
    #system("/kolab/bin/openssl dsaparam 1024 -out dsa-params");
    #system("/kolab/bin/openssl gendsa -out $privreskey dsa-params");
    #system("/kolab/bin/openssl dsa -in $privreskey -pubout -out $pubreskey");
    print "Creating RSA keypair for resource password encryption\n";
    kolab_system("/kolab/bin/openssl genrsa -out $privreskey 1024");
    kolab_system("/kolab/bin/openssl rsa -in $privreskey -pubout -out $pubreskey");
    kolab_system("chown @l_musr@:@l_ngrp@ $pubreskey $privreskey");
    chmod 0660, $privreskey, $pubreskey;
    #unlink( "dsa-params" );
    umask $oldmask;
  }

  print <<'EOS';
Kolab can create and manage a certificate authority that can be
used to create SSL certificates for use within the Kolab environment.
You can choose to skip this section if you already have certificates
for the Kolab server.
EOS

  my $tmp = getUserInput( "Do you want to create CA and certificates", "y", "y", "n");
  if( lc $tmp eq 'n' ) {
    print <<'EOS';
Skipping certificate creation. Please copy your certificate to
@l_prefix@/etc/kolab/cert.pem and private key to
@l_prefix@/etc/kolab/key.pem when the bootstrap script is finished.

EOS
  } else {
    print <<'EOS';
Now we need to create a cerificate authority (CA) for Kolab and a server
certificate. You will be prompted for a passphrase for the CA.
################################################################################
EOS
    kolab_system("$kolab_prefix/etc/kolab/kolab_ca.sh -newca $fqdn");
    kolab_system("$kolab_prefix/etc/kolab/kolab_ca.sh -newkey $fqdn $kolab_prefix/etc/kolab/key.pem");
    kolab_system("$kolab_prefix/etc/kolab/kolab_ca.sh -newreq $fqdn $kolab_prefix/etc/kolab/key.pem $kolab_prefix/etc/kolab/newreq.pem ");
    kolab_system("$kolab_prefix/etc/kolab/kolab_ca.sh -sign $kolab_prefix/etc/kolab/newreq.pem $kolab_prefix/etc/kolab/cert.pem");
    kolab_system("chgrp @l_rusr@ $kolab_prefix/etc/kolab/key.pem;");
    kolab_system("chmod 0640 $kolab_prefix/etc/kolab/key.pem;");
    kolab_system("chgrp @l_rusr@ $kolab_prefix/etc/kolab/cert.pem;");
    kolab_system("chmod 0640 $kolab_prefix/etc/kolab/cert.pem;");
    print <<'EOS';
################################################################################
CA and certificate creation complete.

You can install @l_prefix@/etc/kolab/ca/cacert.pem on your clients to allow them
to verify the validity of your server certificates.

EOS
  }
} else {
  ##### Slave server setup

  print "stop running slapd (if any)\n";
  kolab_system("$kolab_prefix/bin/openpkg rc openldap stop");
  sleep 1;
  kolab_system("$kolab_prefix/bin/openpkg rc openldap stop");
  sleep 1;

  # Make sure that no rogue demons are running
  tryConnect( '127.0.0.1', 389 ) && die "A process is already listening to port 389 (ldap)\n"
    ."Please stop any running ldap server and bootstrap again\n";
  tryConnect( '127.0.0.1', 9999 ) && die "A process is already listening to port 9999 (kolabd)\n"
    ."Please stop any running kolabd and bootstrap again\n";
  if( `ps aux|grep slurpd|grep -v grep` ) {
    print "WARNING: Detected running slurpd processes.\n";
    print " Please make sure the OpenLDAP server is stopped properly!\n";
  }

  # For now we just connect to the remote slapd
 SLAVESTART:
  print "Now some information about the master LDAP server is required:\n\n";
  do { 
      $ldap_uri = getUserInput("URI of master LDAP server (for example ldaps://host.example.com)", 
			       $ldap_uri);
  } until $ldap_uri;
  my $ldapuri = URI->new($ldap_uri) || warn "error: could not parse given uri";
  if( $ldapuri ) {
    $base_dn = join( ',', map { "dc=$_" } split /\./, $ldapuri->host() );
  }
  $base_dn = getUserInput("Base DN of server", $base_dn);
  print "proceeding with base DN $base_dn\n";

  $bind_dn = "cn=manager,cn=internal,$base_dn";
  $bind_pw = getUserInput("Manager password");
  $bind_pw_hash = hashPassword($bind_pw);

  my $confname = "$kolab_prefix/etc/sasl/apps/smtpd.conf";
  copy("$kolab_prefix/etc/kolab/templates/smtpd.conf.template", $confname) || die "could not write to $confname";

  print "Checking server info...\n";
  my $ldap = Net::LDAP->new($ldap_uri, verify => 'none', onerror => 'undef' );
  if (!defined($ldap)) {
    print "Could not connect to ldap server at $ldap_uri, please check your input\n";
    goto SLAVESTART;
  }
  $ldap->bind($bind_dn, password=> $bind_pw) || warn "could not bind to ldap";
  my $mesg = $ldap->search(base=> "$base_dn", scope=> 'exact', filter=> "(objectclass=*)");
  if ($mesg && $mesg->count != 1) {
    print "No $base_dn object found, please check your input\n";
    goto SLAVESTART;
  }
  $php_dn = "cn=nobody,cn=internal,$base_dn";
  $mesg = $ldap->search(base=> $php_dn, scope=> 'exact', filter=> "(objectclass=*)");
  if ($mesg && $mesg->count != 1) {
    print "Nobody object not found, please check your input\n";
    goto SLAVESTART;
  }
  #my $entry = $mesg->entry(0);
  #$php_pw = $entry->get_value( 'userPassword' );

  $calendar_dn = "cn=calendar,cn=internal,$base_dn";
  $mesg = $ldap->search(base=> $php_dn, scope=> 'exact', filter=> "(objectclass=*)");
  if ($mesg && $mesg->count != 1) {
    print "Calendar object not found, please check your input\n";
    goto SLAVESTART;
  }
  #$entry = $mesg->entry(0);
  #$calendar_pw = $entry->get_value( 'userPassword' );

  $mesg = $ldap->search(base=> "k=kolab,$base_dn", scope=> 'exact',
			filter=> "(objectClass=*)");
  if ($mesg && $mesg->count != 1) {
    print "No Kolab object found, please check your input\n";
    goto SLAVESTART;
  }
  my $kolabhosts = $mesg->entry(0)->get_value( 'kolabhost', asref => 1 );
  foreach(@$kolabhosts) {
    if( lc($_) eq lc($fqdn) ) {
	goto SLAVEOK;
    }
  }
  print "$fqdn is not listed on the master, please correct that and try again\n";
  goto SLAVESTART;
 SLAVEOK:

  my $master_host = $ldapuri->host();

  print "Reading nobody and calendar passwords from master, please type in master's root-password when asked\n";
  open( CONF, "ssh -C $master_host 'cat $kolab_prefix/etc/kolab/kolab.conf'|");
  my $conf;
  $conf .= $_ while(<CONF>);
  close(CONF);
  $conf =~ /php_pw : (.*)/;
  $php_pw = $1;
  $conf =~ /calendar_pw : (.*)/;
  $calendar_pw = $1;

  (print "Error reading nobody password" && goto SLAVESTART) unless( $php_pw );
  (print "Error reading calendar password" && goto SLAVESTART) unless( $calendar_pw );

  $fd = IO::File->new($kolab_config, "w+") || die "could not open $kolab_config";
  print $fd "fqdnhostname : $fqdn\n";
  print $fd "is_master : $is_master\n";
  print $fd "base_dn : $base_dn\n";
  print $fd "bind_dn : $bind_dn\n";
  print $fd "bind_pw : $bind_pw\n";
  print $fd "bind_pw_hash : $bind_pw_hash\n";
  print $fd "ldap_uri : $ldap_uri\n";
  print $fd "ldap_master_uri : $ldap_uri\n";
  print $fd "php_dn : $php_dn\n";
  print $fd "php_pw : $php_pw\n";
  print $fd "calendar_dn : $calendar_dn\n";
  print $fd "calendar_pw : $calendar_pw\n";
  undef $fd;
  print "done modifying $kolab_config\n\n";
  chmod 0600, $kolab_config;
  kolab_chown "@l_musr@","@l_mgrp@",$kolab_config;

  print << 'EOS';
Now the master server needs to be stopped briefly while the contents of the LDAP database
is copied over to this slave. Please make sure that this slave is entered into the list 
of kolabhosts on the master before proceeding.
EOS
  kolab_system("ssh -CA $master_host $kolab_prefix/bin/openpkg rc openldap stop");
  kolab_system("ssh -CA $master_host $kolab_prefix/lib/openpkg/tar -C $kolab_prefix/var/openldap -pcf - openldap-data | $kolab_prefix/lib/openpkg/tar -C $kolab_prefix/var/openldap -pxf -");
  kolab_system("ssh -CA $master_host $kolab_prefix/bin/openpkg rc openldap start");

  print "Updating configuration, please ignore any initial errors from kolabconf\n\n";
  my $cfg;
  open(FH, "<$kolab_prefix/etc/rc.conf") || die;
  $cfg .= $_ while (<FH>);
  close(FH);
  
  $cfg =~ s/\n((openldap_url|sasl_authmech|openldap_enable)\S*=[^\n]*)/#$1\n/sg;
  # $cfg .= "openldap_enable=\"no\"\nopenldap_url=\"\"\nsasl_authmech=\"ldap\"\n";
  $cfg .= "\nopenldap_url=\"ldap:// ldaps://\"\nsasl_authmech=\"ldap\"\n";
  
  open(FH, ">$kolab_prefix/etc/rc.conf") || die;
  print FH $cfg;
  close(FH);
  undef $cfg;
  
  print <<'EOS';
If you chose to create a CA on the master server, you will now need to create
a certificate request and copy it to the master to get it signed. If you already
have a certificate for this server, you can choose to skip this section.
EOS
  my $tmp = getUserInput( "Do you want to create a certificate request and sign it", 
			  "y", "y", "n");
  if( lc $tmp eq 'n' ) {
    print <<'EOS';
Skipping certificate creation. Please copy your certificate to
@l_prefix@/etc/kolab/cert.pem and private key to
@l_prefix@/etc/kolab/key.pem when the bootstrap script is finished.

EOS
  } else {
    
    print <<'EOS';
Now we need to create a cerificate request for this slave
and then ssh to the master server to have the request signed.
You will be asked multiple times for the root password of the
master server and the passphrase for the CA key on the master.
################################################################################
EOS

    # Create cert req
    kolab_system("$kolab_prefix/etc/kolab/kolab_ca.sh -newkey $fqdn $kolab_prefix/etc/kolab/key.pem");
    kolab_system("$kolab_prefix/etc/kolab/kolab_ca.sh -newreq $fqdn $kolab_prefix/etc/kolab/key.pem $kolab_prefix/etc/kolab/newreq.pem ");
    # Log into master and sign cert request
    kolab_system("scp $kolab_prefix/etc/kolab/newreq.pem $master_host:$kolab_prefix/etc/kolab/$fqdn-req.pem");
    kolab_system("ssh -CA $master_host \"$kolab_prefix/etc/kolab/kolab_ca.sh -sign $kolab_prefix/etc/kolab/$fqdn-req.pem $kolab_prefix/etc/kolab/$fqdn.pem;\"");
    kolab_system("scp $master_host:$kolab_prefix/etc/kolab/$fqdn.pem $kolab_prefix/etc/kolab/cert.pem");
    kolab_system("ssh -CA $master_host \"rm $kolab_prefix/etc/kolab/$fqdn.pem $kolab_prefix/etc/kolab/$fqdn-req.pem\"");
    die("Creation of $kolab_prefix/etc/kolab/cert.pem failed") unless -f "$kolab_prefix/etc/kolab/cert.pem";
    kolab_system("chgrp @l_rgrp@ $kolab_prefix/etc/kolab/key.pem;");
    kolab_system("chmod 0640 $kolab_prefix/etc/kolab/key.pem;");
    kolab_system("chgrp @l_rgrp@ $kolab_prefix/etc/kolab/cert.pem;");
    kolab_system("chmod 0640 $kolab_prefix/etc/kolab/cert.pem;");
    
    print <<'EOS';
################################################################################
Certificate creation done!

EOS
  }

  print <<'EOS';
To be able to encrypt and decrypt passwords for group and resource accounts
we need to copy the RSA keypair used for that purpose from the master server.
EOS
  my $privreskey = "$kolab_prefix/etc/kolab/res_priv.pem";
  my $pubreskey  = "$kolab_prefix/etc/kolab/res_pub.pem";
  kolab_system("scp $master_host:$privreskey "
	       ."$master_host:$pubreskey "
	       ."$kolab_prefix/etc/kolab/");
  kolab_system("chown @l_musr@:@l_ngrp@ $pubreskey $privreskey");
  chmod 0660, $privreskey, $pubreskey;
  kolab_system("$kolab_prefix/sbin/kolabconf -n");

  $fd = IO::File->new($kolab_config, "w+") || die "could not open $kolab_config";
  print $fd "fqdnhostname : $fqdn\n";
  print $fd "is_master : $is_master\n";
  print $fd "base_dn : $base_dn\n";
  print $fd "bind_dn : $bind_dn\n";
  print $fd "bind_pw : $bind_pw\n";
  print $fd "ldap_uri : ldap://127.0.0.1\n";
  print $fd "ldap_master_uri : $ldap_uri\n";
  print $fd "php_dn : $php_dn\n";
  print $fd "php_pw : $php_pw\n";
  print $fd "calendar_dn : $calendar_dn\n";
  print $fd "calendar_pw : $calendar_pw\n";
  undef $fd;
  print "done modifying $kolab_config\n\n";
  chmod 0600, $kolab_config;
}

#system("$kolab_prefix/etc/kolab/kolab_sslcert.sh $fqdn");
print "kolab is now ready to run!\n";
print "please run '$kolab_prefix/bin/openpkg rc all start'\n";
print ("Use login=manager and passwd=$bind_pw when you log into\n");
print ("the webinterface https://$fqdn/admin !\n");
