#!/bin/bash
###############################################################################
##
##      Copyright (c) 2014 Avaya Inc All Rights Reserved
##      THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AVAYA INC
##
##      The copyright notice above does not evidence any
##      actual or intended publication of such source code.
##
###############################################################################
#

# check if user is root
[ $UID -eq 0 ] || exec sudo $0 "$@"

# -----------------------------------------------------------------------------
# definitions
#

CSR_CMD="/opt/util/bin/csrmanage"
CERT_CMD="/opt/util/bin/certmanage"

export CCSAES_OFFERTYPE=TURNKEY  #workaround for VSP

# -----------------------------------------------------------------------------
# usage
#

function usage()
{
    echo ""
    echo "usage: $0
		 [ createCSR -subj 'string' -keysize number -hash digest -name string [-ca] ]
                 [ printCSR | decodeCSR | deleteCSR -name string ]
                 [ listCSR | generateCSR ]
                 [ -h ]
       createCSR   : Create a new key and CSR with given keysize and subj
       listCSR     : Print a colon sperated list of all CSRs names
       printCSR    : Print the Base64 content of the CSR file of a name
       decodeCSR   : Print the decoded content of the CSR file of a name
       deleteCSR   : Delete CSR file and key of a name
       generateCSR : Create a new key and CSR interactively
       -subj    : New CSR subject line. Use quotes to protect the string
       -keysize : New CSR key size (2048 or 3072)
       -hash    : Type of message digest to use (sha256, sha384, or sha512)
       -ca      : New CSR is capable for a certificate authority
       -name  : CSR name for print, decode and delete
       -h       : Usage (this)"
    echo ""
    exit -1
}

# -----------------------------------------------------------------------------
# _RUN
#      Execute a command with redirected stdin, stdout and stderr.
#      This is necessary because some patches restarts services that not
#      release their access to stdin, stdout or stderr. This causes blocking of
#      the ssh client on the other side.
#

function _RUN()
{
    _RUN_STDOUT=$(mktemp)
    _RUN_STDERR=$(mktemp)
    "$@" </dev/null >${_RUN_STDOUT} 2>${_RUN_STDERR} ; _RUN_RC=$?
    cat ${_RUN_STDOUT} ; rm -f ${_RUN_STDOUT}
    cat ${_RUN_STDERR} >&2 ; rm -f ${_RUN_STDERR}
    return ${_RUN_RC}
}

function do_operation()
{
    RC=0
    if [[ "$type" == "csr" ]];then
        _RUN $CSR_CMD "$@"
    elif [[ "$type" == "cert" ]];then
	_RUN $CERT_CMD "$@"
    fi

    exit ${RC}
}

function generateCSR()
{

  read -p "Country Name (2 letter code) : " country
  read -p "State or Province Name (full name) : " state
  read -p "Locality name (eg: city) : " locality
  read -p "Organization name (eg; company) : " org
  read -p "Organization Unit Name (eg: section) : " orgunit
  read -p "Common Name (eg:your name or server\'s hostname ) : " cname
  read -p "Unique CSR identifier (any unique name) : " name
  read -p "Key size(2048, 3072 or 4096) : " keysize
  read -p "Digest algorithm(sha256, sha384, or sha512) : " digest
  read -p "Is this a CA Certificate?(yes/no) : " CA
  CA=${CA,,}
  subject="/C=$country/ST=$state/L=$locality/O=$org/OU=$orgunit/CN=$cname"
  if [ "$CA" = "y" ] || [ "$CA" = "yes" ];then
    do_operation create -subj "$subject" -keysize $keysize -hash $digest -name "$name" -ca
  else
    do_operation create -subj "$subject" -keysize $keysize -hash $digest -name "$name"
  fi

}


# -----------------------------------------------------------------------------
# main
#
mode="$1"
if [[ "$mode" =~ CSR ]];then
   type="csr"
   mode=${mode%"CSR"}
   case "$mode" in
	create)
	   do_operation create "${@:2}";;
	list)
	   arglist="${@:2}"
	   if [ -z "$arglist" ];then
	        do_operation list
	   else
		echo "Invalid argument(s).Check usage."
	   fi
	   ;;
	print)
           do_operation print "${@:2}";;
	decode)
           do_operation decode "${@:2}";;
	delete)
           do_operation delete "${@:2}";;
	generate)
           arglist="${@:2}"
           if [ -z "$arglist" ];then
                generateCSR
           else
                echo "Invalid argument(s).Check usage."
           fi
           ;;
	*)
	   usage
	   exit 1;;
   esac
elif [[ "$mode" =~ CERT ]];then
   type="cert"
   mode=${mode%"CERT"}
   shift

else
   echo "Invalid argument(s).Check usage."
   usage
fi

exit 0
