#! /bin/bash
#=========================================================================
# Copyright (C) GemTalk Systems 1986-2024.  All Rights Reserved..
#
# Name - newuserCA
# Installed as - newuserCA
#
# Written By: Martin McClure and Norm Green
#
# Purpose - Create a certificate authority (CA) to issue certificates for
#           GemStone hosts.
#
# 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 user CA certificate for the given stone name

cmd=`basename $0`

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

# defaults
daysValid=30
stoneName=""

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

# 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

checkStoneExists $stoneName
checkDaysValid $daysValid

if [ -f "${userCaCert}" ]; then
    echo "[Error]: user CA certificate already exists (${userCaCert})" >&2
    exit 1
fi

createIntermediateCa ${userCaPrivKey} ${userCaCsr} ${userCaCert} ${daysValid} userCA ${userCaCrl}
