#!/bin/bash
# 
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2013, 2014, 2016 Synacor, Inc.
#
# 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,
# version 2 of the License.
#
# 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, see <https://www.gnu.org/licenses/>.
# ***** END LICENSE BLOCK *****
# 

source `dirname $0`/../bin/zmshutil || exit 1
zmsetvars

keyattr="zimbraSshPublicKey"

zmprov="/opt/zimbra/bin/zmprov -m -l"

keyfile="/opt/zimbra/.ssh/zimbra_identity"

mkdir -p /opt/zimbra/.ssh

if [ ! -d "/opt/zimbra/.ssh" ]; then
  echo "Unable to create /opt/zimbra/.ssh."
  exit 1
fi

chmod 700 /opt/zimbra/.ssh

rm -f ${keyfile}

keytype=${1:-rsa}

if [ $keytype != "rsa" ]; then
	echo "Bad keytype: $keytype"
	echo ""
	exit 1
fi

ssh-keygen -f ${keyfile} -b 2048 -N '' \
	-t ${keytype} -C ${zimbra_server_hostname}

# Starting with OpenSSH 7.8 by default, the key is created with the OpenSSH private key format instead of the OpenSSL PEM format.
# Check the format of KEY and convert to OpenSSL PEM format.
grep "BEGIN OPENSSH PRIVATE KEY" ${keyfile} > /dev/null 2>&1
  if [ $? = 0 ]; then
     ssh-keygen -p -m PEM -f ${keyfile}  -b 2048 -N '' -t ${keytype} -C ${zimbra_server_hostname}
  fi
pubkey=`cat ${keyfile}.pub`

${zmprov} ms ${zimbra_server_hostname} ${keyattr} "${pubkey}"
