#! /bin/bash
# set -xv
#=========================================================================
# Copyright (C) GemTalk Systems 1986-2024.  All Rights Reserved..
#
# Name - revokeuser
# Installed as - revokeuser
#
# Written By: Martin McClure and Norm Green
#
# Purpose -
#
# Revokes the certificate for a Database user.
#
# Takes the following actions:
#
# 1 - Revokes the user's cert with the CA
# 2 - Adds the user's cert to the CRL for the userCA.
# 3 - Regenerates the CRL for the userCA (old CRL is overwritten, not preserved).
# 4 - Renames the user's cert directory and moves it into the revoked directory.
#     The new directory name is the old name with ".revoked.$TS" appended where $TS
#     is a timestamp.
#     Example: Before revoking DataCurator, the cert and private key are in:
#       /home/normg/certs_new/stones/norm/users/DataCurator/*.pem
#     After revoking the cert, this directory is moved and renamed to:
#       /home/normg/certs_new/stones/norm/users/revoked/DataCurator.revoked.Mar-23-2018-14-02-10/*.pem
#
# 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.
#
#=========================================================================
#### Revoke a user certificate

cmd=`basename $0`

usage(){
    echo "Usage: $cmd -h | -s <stoneName>  <userName>" >&2
    exit 1
}

stoneName=""
daysValid=30
ARGC=$#

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

shift $((OPTIND-1))
userName=$1

# 48065
if [ $OPTIND -ne $ARGC ]; then
    echo "[Error]: userName 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

if [ -z "$userName" ]; then
    echo "[Error]: Missing username argument" >&2
    usage
fi

verifyStoneExistsForRm $stoneName
verifyUserExistsForRm $userName

userDir=${thisStonesDir}/users/${userName}

if [ ! -f ${userCaCert} ]; then
    echo "[Error]: Cannot find the user CA cert for stone '$stoneName'." >&2
    exit 1
fi

userCert=${userDir}/${userName}.cert.pem

revokeCert ${userCaPrivKey} ${userCaCert} ${userCert} ${userCaCrl}
