#!/usr/local/bin/bash
##
## create-ssl-keystore.sh
##
##  Copyright (c) 2004 SIPfoundry, Inc.
##  License by SIPfoundry under the LGPL license.
##  
##  Copyright (c) 2004 Pingtel Corp.
##  Licensed to SIPfoundry under a Contributor Agreement.
##

Action=CREATE
SslDir="/usr/local/etc/sipxpbx/ssl"
Certificate="$SslDir/ssl.crt"
Key="$SslDir/ssl.key"
KeyStorePkcs12="$SslDir/.ssl.p12"
KeyStore="$SslDir/.ssl.keystore"
Password="changeit"
KeyStoreFilesChecksum="${KeyStore}-contents.md5"
Checksum=""
PreviousChecksum=""
openssl="/usr/bin/openssl"

Checksum=`cat $Certificate $Key | /sbin/md5 -r | awk '{print $1}'`
if [ -f $KeyStoreFilesChecksum ]; then
  if [ -f $KeyStore ]; then
    PreviousChecksum=`cat $KeyStoreFilesChecksum`
    if [ "x$Checksum" = "x$PreviousChecksum" ]; then
      echo "Creating $KeyStore was skipped, previous checksum of contents matched"
      exit 0;
    fi
  fi
fi

rm $KeyStorePkcs12 2> /dev/null

caname="`$openssl x509 -noout -text -in $Certificate |\
           grep Issuer: | sed -e 's;.*CN=;;' -e 's;/Em.*;;'`"

servername="`$openssl x509 -noout -text -in $Certificate |\
           grep Subject: | sed -e 's;.*CN=;;' -e 's;/Em.*;;'`"

$openssl pkcs12 -export \
  -password "pass:$Password" \
  -in $Certificate \
  -inkey $Key \
  -name "$servername" \
  -caname "$caname" \
  -out $KeyStorePkcs12 || exit 1

rm $KeyStore 2> /dev/null
JavaCmd=`/usr/local/bin/sipx-config --java`
echo -e "$Password\n$Password" | 
  $JavaCmd \
  -classpath /usr/local/share/sipxpbx/lib/sipxconfig.jar \
  org.mortbay.util.PKCS12Import $KeyStorePkcs12 $KeyStore

#echo -e "$Password\n$Password" | 
#  $JavaCmd \
#  -classpath /usr/local/share/sipxpbx/lib/sipxconfigjetty-*.jar \
#  org.mortbay.util.PKCS12Import $KeyStorePkcs12 $KeyStore

echo $Checksum > ${KeyStoreFilesChecksum}
