#! /bin/bash
#set -xv
#=========================================================================
# Copyright (C) GemTalk Systems 1986-2024.  All Rights Reserved..
#
# Name - rmhost
# Installed as - rmhost
#
# Written By: Martin McClure and Norm Green
#
# Purpose -
#
# Remove all certificates for a given host for a given stone.
#
# Requirements -
#
# The following environment variables must be defined:
#
# GEMSTONE_CERT_DIR - A directory where newly created certificates and
#                     subdirectories will be placed.
#
#=========================================================================

cmd=`basename $0`

usage(){
    echo "Usage: $cmd -h | -s <stoneName> [-f] <hostname>" >&2
    echo "      -h - show this help screen" >&2
    echo "      -f - force. Do not prompt for confirmation" >&2
    exit 1
}

ARGC=$#
force=0

while getopts "fhs:i:a:" opt; do
    case $opt in
	h)
	    usage
	    ;;
        s)
          stoneName=${OPTARG}
          ;;
        f)
          force=1
          ;;
        \?)
          usage
          ;;
        :)
          echo "[Error]: 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."
    exit 1
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

verifyStoneExistsForRm ${stoneName}

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

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

if [ ! -d ${hostDir} ]; then
    echo "[Error]: No host named '$hostName' exists for the stone named '$stoneName'" >&2
    exit 1
fi

if [ $force -eq 0 ]; then
  echo "[Warning]: All certificates for host '$hostName' for use with stone '$stoneName' will be deleted."
  confirmAction     
fi

dorm ${hostDir}
exit $?
