#! /bin/bash
#set -xv
#=========================================================================
# Copyright (C) GemTalk Systems 1986-2024.  All Rights Reserved..
#
# Name - newstone
# Installed as - newstone
#
# Written By: Martin McClure and Norm Green
#
# Purpose - Create the directory structure in the GEMSTONE_CERT_DIR
#           directory and create the self signed certificate and private
#           key for the stone. It is an error if certificates for the
#           specified stone name already exist.
#
# 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.
#
#=========================================================================

cmd=`basename $0`

usage(){
    echo "Usage: $cmd [-d <daysValid>] stoneName" >&2
    echo "  where daysValid is the number of days the stone CA cert will be valid (default: 30 days)" >&2
    exit 1
}

# defaults
daysValid=30
stoneName=""
ARGC=$#

while getopts "hd:" opt; do
    case $opt in
	d)
	    daysValid=${OPTARG}
	    ;;
	h)
	    usage
	    ;;
        \?)
          usage
          ;;
        :)
          echo "Option -${OPTARG} requires an argument." >&2
          usage
          ;;
    esac
done
shift $((OPTIND-1))
stoneName=$1

# 48065
if [ $OPTIND -ne $ARGC ]; then
    echo "[Error]: stoneName must be the last argument."
    usage
fi

# 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

checkDaysValid $daysValid

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

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

## Self-signed certificate
doopenssl req -x509 -config ${configDir}/selfSigned.conf \
	   -days ${daysValid} -key ${stoneCaPrivKey} -out \
	   ${stoneCaCert} \
	   -subj /gemstone_CertificateType=stoneCA/gemstone_StoneName=${stoneName}


exit 0
