#! /bin/bash
# set -xv
#=========================================================================
# Copyright (C) GemTalk Systems 1986-2024.  All Rights Reserved..
#
# Name - revokehost
# Installed as - revokehost
#
# Written By: Martin McClure and Norm Green
#
# Purpose -
#
# Revokes the certificate for a host.
#
# Takes the following actions:
#
# 1 - Revokes the host's cert with the CA
# 2 - Adds the host's cert to the CRL for the hostCA.
# 3 - Regenerates the CRL for the hostCA (old CRL is overwritten, not preserved).
# 4 - Renames the host'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 host jupiter, the cert and private key are in:
#       /home/normg/certs_new/stones/norm/hosts/jupiter/*.pem
#     After revoking the cert, this directory is moved and renamed to:
#       /home/normg/certs_new/stones/norm/hosts/revoked/jupiter.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 host certificate

cmd=`basename $0`

usage(){
    echo "Usage: $cmd -h | -s <stoneName>  <hostName>" >&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))
hostName=$1

# 48065
if [ $OPTIND -ne $ARGC ]; then
    echo "[Error]: hostName 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 "$hostName" ]; then
    echo "[Error]: Missing hostname argument" >&2
    usage
fi

verifyStoneExistsForRm $stoneName
verifyHostExistsForRm $hostName

hostDir=${thisStonesDir}/hosts/${hostName}

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

hostCert=${hostDir}/${hostName}.cert.pem

revokeCert ${hostCaPrivKey} ${hostCaCert} ${hostCert} ${hostCaCrl}
