#!/bin/sh
#******************************************************************************
# Copyright 1991-2004 by ADIC, Inc.  All rights reserved.
# No part of this work may be reproduced or transmitted in any
# form or by any means, electronic or mechanical, including
# photocopying and recording, or by any information storage
# or retrieval system, except as may be expressly permitted by
# the 17 U.S.C. section 101, et. seq., or in writing by
# ADIC, Inc.
#*******************************************************************************
#
# Create a Certificate Authority certificate in pem format. Allows certificate 
# to contain the below descriptive information. Places certificate and key 
# in $OPENSSLHOME/cert. A Certificate Authority (CA) cert is require to 
# create a library key.
#
#*******************************************************************************
#  $Log: src/bin/mkca  $
#  Revision 1.5 2005/10/17 08:20:34MDT astoner 
#  make the certificate authority organization and company information generic
#  Revision 1.4 2004/11/11 09:07:25MST astoner 
#  add LD_LIBRARY_PATH for shared openssl
#  Revision 1.3 2004/11/10 10:42:06MST astoner 
#  misc changes for busybox linux
#  Revision 1.2 2004/11/10 10:32:30MST astoner 
#  add OPENSSL_CONF entry
#  Revision 1.1 2004/11/08 13:57:55MST astoner 
#  Initial revision
#  Member added to project e:/mks/projects/predatorssl/predatorssl.pj
#
#*******************************************************************************


if [ -z "${1}" ] ; then
   echo "Usage: ${0} <openssl home>"
   exit 1
fi

export OPENSSL_HOME="${1}"
export OPENSSL_CONF=${OPENSSL_HOME}/openssl.cnf
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${OPENSSL_HOME}/lib
export ADIC_CA_CERT="ADIC_CA.pem"
export ADIC_CA_KEY="ADIC_KEY.pem"

export KEY_LOC="${OPENSSL_HOME}/private"
export CERT_LOC="${OPENSSL_HOME}/certs"

SERIAL_HOME="${OPENSSL_HOME}/serial"
SERIAL_FILE="${OPENSSL_HOME}/serial/certSerial"

#
# Make required directories if they don't exist
#

if [ ! -d "${KEY_LOC}" ] ; then
   mkdir -p ${KEY_LOC}
fi

if [ ! -d "${CERT_LOC}" ] ; then
   mkdir -p ${CERT_LOC}
fi

if [ ! -d "${SERIAL_HOME}" ] ; then
   mkdir -p ${SERIAL_HOME}
   echo "01" > ${SERIAL_FILE}
fi

#
# Meta data for record in ADIC Certificate Authority
#
export COUNTRY="US"
export STATE="NA"
export CITY="NA"
export COMPANY="Generic Organization"
export ORG_UNIT="Generic Self Signed CA"
export HOST="Top level Cert"
export EMAIL="NA"

#
# remove the existing files before creating
#

if [ -f "${KEY_LOC}/${ADIC_CA_KEY}" ] ; then
   rm -f "${KEY_LOC}/${ADIC_CA_KEY}"
fi

if [ -f "${CERT_LOC}/${ADIC_CA_CERT}" ] ; then
   rm -f "${CERT_LOC}/${ADIC_CA_CERT}"
fi

${OPENSSL_HOME}/bin/openssl req -passout pass:password -keyout ${KEY_LOC}/${ADIC_CA_KEY} -out ${CERT_LOC}/${ADIC_CA_CERT} -new -x509 <<EOF
${COUNTRY}
${STATE}
${CITY}
${COMPANY}
${ORG_UNIT}
${HOST}
${EMAIL}


EOF

chmod 0400 ${KEY_LOC}/${ADIC_CA_KEY}

