#! /bin/bash
#=========================================================================
# Copyright (C) GemTalk Systems 1986-2024.  All Rights Reserved..
#
# Name - newstone_csr
# Installed as - newstone_csr
#
# Written By: Martin McClure and Norm Green
#
# Purpose - Create the directory structure in the GEMSTONE_CERT_DIR
#           directory and create certificate signing request (CSR) for
#           the stone certificate. The CSR can then be passed to some
#           CA to generate the stone certificate.
#
# Requirements -
#
# The following environment variables must be defined:
#
# GEMSTONE or OPENSSL_PREFIX_DIR
# GEMSTONE_CERT_DIR - A directory where newly created certificates and
#                     subdirectories will be placed.
#
#=========================================================================

#### Create the CSR for the stone CA

cmd=`basename $0`

usage(){
    echo "Usage: $cmd <stoneName>" >&2
    exit 1
}

stoneName=""
while getopts "h" opt; do
    case $opt in
	h)
	    usage
	    ;;
        \?)
          usage
          ;;
    esac
done
shift $((OPTIND-1))
stoneName=$1

# 47501 - handle symlinks
fullPath=`readlink -e -n $0`
scriptDir=`dirname $fullPath`
if [ ! -f $scriptDir/environment.sh ]; then
    echo "[Error]: Cannot find environment.sh setup script"
    exit 1
fi
. ${scriptDir}/environment.sh

if [ -d "${thisStonesDir}" ]; then
    errStoneExists
else
    createStoneDir
fi

## Stone CA private key
doopenssl genpkey -out ${stoneCaPrivKey} -algorithm RSA \
	   -pkeyopt rsa_keygen_bits:${rsaKeyBits}

## Stone CA CSR
doopenssl req -config ${configDir}/stone_csr.conf -new \
	   -key ${stoneCaPrivKey} -out \
	   ${stoneCaCsr} \
	   -subj /gemstone_CertificateType=stoneCA/gemstone_StoneName=${stoneName}

echo "[Info]: Successfully created CSR for stone $stoneName."
echo "[Info]:   Filename=${stoneCaCsr}"
echo "[Info]: Once signed, please copy the certificate file to:"
echo "[Info]:   $stoneCaCert"

