#!/bin/bash
# 
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1
# 
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 ("License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.zimbra.com/license
# 
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and limitations
# under the License.
# 
# The Original Code is: Zimbra Collaboration Suite Server.
# 
# The Initial Developer of the Original Code is Zimbra, Inc.
# Portions created by Zimbra are Copyright (C) 2005, 2006 Zimbra, Inc.
# All Rights Reserved.
# 
# Contributor(s):
# 
# ***** END LICENSE BLOCK *****
# 

BASE=/opt/zimbra/ssl/ssl

JAVA_HOME=/opt/zimbra/java

TOMCAT=/opt/zimbra/tomcat/conf

CONF=/opt/zimbra/conf
TCONF=/opt/zimbra/tomcat/conf

usage() {
  echo "$0 mta <certfile> <keyfile>"
  echo "$0 mailbox [<certfile>]"
  echo "  Default <certfile> is ${BASE}/server/tomcat.crt"
  exit 1
}

if [ $# = 0 ]; then
  usage
fi

APP=$1
shift

CERTFILE=$1
KEYFILE=$2

if [ "x$CERTFILE" = "x" ]; then
	CERTFILE=${BASE}/server/tomcat.crt
fi

if [ ! -f $CERTFILE ]; then
	echo "ERROR - $CERTFILE not found!"
	exit 1
fi

mkdir -p ${BASE}/server
mkdir -p ${BASE}/cert
mkdir -p ${BASE}/ca


getHostInfo() {

	platform=`/opt/zimbra/libexec/get_plat_tag.sh`
	if [ "x$platform" = "xMACOSX" -o "x$platform" = "xMACOSXx86" ]; then
		HH=`hostname`
		return
	else
		H=`hostname --fqdn`
	fi

	# $H=$H.zimbrasys.com

	HH=`echo $H | grep '\.'`

	if [ "x$HH" = "x" ]; then
		echo "Error - fully qualified host name not found - please correct"
		exit
	fi

}

importCert() {

	echo "** Importing server cert"
	echo

	if [ $APP = "mailbox" ]; then
		keytool -import -alias tomcat -keystore ${TCONF}/keystore \
			-trustcacerts -file ${CERTFILE} -storepass zimbra
	else
		cp -f $CERTFILE ${CONF}/smtpd.crt
		cp -f $KEYFILE ${CONF}/smtpd.key
	fi

}

getHostInfo

importCert
