#!/usr/bin/perl -w

#----------------------------------------------------------------------
# copyright (C) 2002 Mitel Networks Corporation
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 General Public License for more details.
# 		
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
# 
# Technical support for this program is available from Mitel Networks 
# Please visit our web site www.mitel.com/sme/ for details.
#----------------------------------------------------------------------
package esmith;

use strict;
use Errno;
use esmith::util;
use esmith::ConfigDB;
use FileHandle;
use File::Copy;

# Create IMAP pem certificate file, essentially by concatenating the
# key and certificate files used by http SSL.

my $conf = esmith::ConfigDB->open();
my $domain = $conf->get('DomainName')->value || "localdomain";
my $hostname = $conf->get('SystemName')->value || "localhost";

my $key = $conf->get('modSSL')->prop('key') ||
	    "/home/e-smith/ssl.key/$hostname.$domain.key";

my $crt = $conf->get('modSSL')->prop('crt') ||
	    "/home/e-smith/ssl.crt/$hostname.$domain.crt";

chdir "/var/service/imap/ssl"
    or die "Could not chdir to /var/service/imap/ssl: $!";

my $pemfile = "imapd.pem";
my $tempfile = "$pemfile.$$";
my $pem = new FileHandle "> $tempfile";
die "Couldn't open temp pem cert file: $!" unless defined $pem;

copy($key, $pem) or die("Error writing key to pem cert file: $!");
print $pem "\n" or die("Error writing separator to pem cert file: $!");
copy($crt, $pem) or die("Error writing crt to pem cert file: $!");
$pem->close or die("Error closing pem cert file: $!");
chmod 0640, $tempfile;
esmith::util::chownFile('root', 'stunnel', $tempfile);
rename("$tempfile", "$pemfile")
    or die "Error replacing pem cert file: $!";

exit (0);
