#! /bin/sh

#
# Portions of this file Copyright 1999-2005 University of Chicago
# Portions of this file Copyright 1999-2005 The University of Southern California.
#
# This file or a portion of this file is licensed under the
# terms of the Globus Toolkit Public License, found at
# http://www.globus.org/toolkit/download/license.html.
# If you redistribute this file, with or without
# modifications, you must include this notice in the file.
#


# catch the kill signal (ctrl-c) and do cleanup
trap do_trap 1 2 3 6 9 13 15

if test "`echo -n \"testecho\"`" = "testecho"; then
    ECHOOPTION=" -n "
    ECHOTAIL=""
else
    ECHOOPTION=""
    ECHOTAIL='\c'
fi

recho() {

    echo $ECHOOPTION $@ $ECHOTAIL
}

check_expired() {
    
    d=$@
    
    year=`echo ${d} | ${GLOBUS_SH_SED-sed} -e "s|[^0-9]*[0-9]*[ ][0-9]*:[0-9]*:[0-9]*[ ]\([0-9]*\).*|\1|"`

    cyear=`${GLOBUS_SH_DATE-date} +%Y`
    
    if test ${year} -lt ${cyear}; then
        echo "1"
    elif test ${year} -gt ${cyear}; then
        echo "0"
    fi

    month=`echo ${d} | ${GLOBUS_SH_SED-sed} -e "s|\([^0-9]*\).*|\1|"`
    if test "${month}" = "Jan"; then
        monnum=01
    elif test "${month}" = "Feb"; then
        monnum=02
    elif test "${month}" = "Mar"; then
        monnum=03
    elif test "${month}" = "Apr"; then
        monnum=04
    elif test "${month}" = "May"; then
        monnum=05
    elif test "${month}" = "Jun"; then
        monnum=06
    elif test "${month}" = "Jul"; then
        monnum=07
    elif test "${month}" = "Aug"; then
        monnum=08
    elif test "${month}" = "Sep"; then
        monnum=09
    elif test "${month}" = "Oct"; then
        monnum=10
    elif test "${month}" = "Nov"; then
        monnum=11
    elif test "${month}" = "Dec"; then
        monnum=12
    else
        monnum=00
    fi

    cmonnum=`date +%m`

    if test ${monnum} -lt ${cmonnum}; then
       echo "1" 
    elif test ${monnum} -gt ${cmonnum}; then
       echo "0" 
    fi

    day=`echo ${d} | ${GLOBUS_SH_SED-sed} -e "s|[^0-9]*\([0-9]*\).*|\1|"`

    cday=`date +%d`

    if test ${day} -lt ${cday}; then
       echo "1" 
    elif test ${day} -gt ${cday}; then
       echo "0" 
    fi
 
    hour=`echo ${d} | ${GLOBUS_SH_SED-sed} -e "s|[^0-9]*[0-9]*[ ]\([0-9]*\):[0-9]*:[0-9]*.*|\1|"`

    chour=`date +%H`

    if test ${hour} -lt ${chour}; then
       echo "1" 
    elif test ${hour} -gt ${chour}; then
       echo "0"  
    fi

    min=`echo ${d} | ${GLOBUS_SH_SED-sed} -e "s|[^0-9]*[0-9]*[ ][0-9]*:\([0-9]*\):[0-9]*.*|\1|"`

    cmin=`date +%M`

    if test ${min} -lt ${cmin}; then
        echo  "1"
    elif test ${min} -gt ${cmin}; then
        echo "0"
    fi

    sec=`echo ${d} | ${GLOBUS_SH_SED-sed} -e "s|[^0-9]*[0-9]*[ ][0-9]*:[0-9]*:\([0-9]*\).*|\1|"`

    csec=`date +%S`

    if test ${sec} -lt ${csec}; then
        echo "1"
    elif test ${sec} -gt ${csec}; then
        echo  "0"
    fi

    echo "0"
}


############################################################
# main code section
############################################################
if test -z "${GLOBUS_LOCATION}"; then
    echo ""
    echo "ERROR: Please set GLOBUS_LOCATION to the" 
    echo "Globus installation directory before"
    echo "running this script"
    echo ""
    exit 1
fi

. ${GLOBUS_LOCATION}/libexec/globus-script-initializer
globus_source ${libexecdir}/globus-sh-tools.sh

PROGRAM_NAME=`echo $0 | ${GLOBUS_SH_SED-sed} 's|.*/||g'`

short_usage="$PROGRAM_NAME [-help] -in <req> -out <cert> [ options ...]"

openssl_options=""

long_usage () {
    ${GLOBUS_SH_CAT-cat} >&2 <<EOF

${short_usage}

  Expects a certificate request as input from the -in argument, and prints
  the signed certificate to file specified by -out.

  Options:
    -force                   : Sign a certificate request with subject that
                               matches an already signed certificate.
    -dir <cadir>             : Set the configure directory of the CA
    -in  <cert req>          : The cert request to sign.
    -out <signed cert>       : The newly signed cert.  

    -<openssl option>        : Any of the options allowed with the 
                               openssl ca command.  Example:
                               
			       -passin pass:<password>

                               Specify the password for the CA private key if 
                               you don't care about security.  
                               Other -passin options also exist,
			       see openssl manpage for further details.

    -openssl-help            : List possible options to the openssl ca command and exit

EOF
}

. $libexecdir/globus-args-parser-header

readCommandLine() {

    while test -n "$1" 
    do
        case $1 in
            -\?|-h|-help|-usage)
                long_usage
                exit 0
                ;;
            -force)
                force_sign="true"
                shift;
                ;;
            -dir)
                shift;
                GRID_CA_DIR=$1;
                shift;
                ;;
            -in)
                shift;
                INPUT_REQ_FILE=$1;
                shift;
                ;;
            -out)
                shift;
                SIGNED_OUTPUT_FILE=$1;
                shift;
                ;;
            -openssl-help)
                shift;
		${GLOBUS_LOCATION}/bin/openssl ca -help
		exit;
		;;
	    *)
                openssl_options="$openssl_options $1"
                shift;
                ;;
        esac
    done
    
    if test -z "$INPUT_REQ_FILE"; then
        echo ""
        echo "ERROR: Please specify a request file using the -in option"
        echo ""
        exit 1
    else
        if test ! -r ${INPUT_REQ_FILE}; then
            echo ""
            echo "ERROR: The file: ${INPUT_REQ_FILE} is not readable"
            echo ""
            exit 1
        fi
    fi

    if test -z "$SIGNED_OUTPUT_FILE"; then
        echo ""
        echo "ERROR: Please specify a output file using the -out option"
        echo ""
        exit 1
    fi
}

do_trap() {

    echo ""
    echo "Normal program execution interrupted.  Exiting."
    echo ""
    do_cleanup
    exit 1
}

do_cleanup() {

    ${GLOBUS_SH_RM-rm} -f ${tmp_output}

    ${GLOBUS_SH_RM-rm} -f ${TMP_REQ_FILE} ${TMP_CERT_FILE}
}

do_password_input() {
    if test $need_password_input; then
        ${GLOBUS_SH_STTY-stty} -echo
        echo ""
        echo $@
        recho "please enter the password for the CA key: "
    fi
}        

end_password_input() {
    if test $need_password_input; then
        ${GLOBUS_SH_STTY-stty} echo
        echo ""
    fi
}

do_sign() {
 
do_password_input "To sign the request"
tmp_output=/tmp/tmp_output.$$
${openssl_cmd} ca $openssl_options -batch -config ${grid_ca_conf} \
                  -in ${TMP_REQ_FILE} -out ${TMP_CERT_FILE} \
                  > $tmp_output 2>&1

openssl_result=$?
end_password_input
 
# check to see if an error occurred while signing
if test ${openssl_result} != 0; then

    # check that a certificate with the same subject has not
    # already been signed
    already_signed=`${GLOBUS_SH_GREP-grep} \
                        "ERROR:There is already a certificate" \
                        ${tmp_output}`
    already_signed2=`${GLOBUS_SH_GREP-grep} \
                        "unique_subject = \"yes\"" \
                        ${tmp_output}`
    if test -n "${already_signed}" || test -n "${already_signed2}"; then

        subj_tmp_output=/tmp/tmp_output.$$
        ${openssl_cmd} req -noout -in ${INPUT_REQ_FILE} \
                           -subject > ${subj_tmp_output} 2>&1
        res=$?
        if test $res != 0; then
            echo ""
            echo "ERROR: Failed to get subject of request ${INPUT_REQ_FILE}"
            echo ""
            do_cleanup
            exit 1
        fi
        
        req_subj=`cat ${subj_tmp_output} | ${GLOBUS_SH_GREP-grep} "subject=" \
                                 | ${GLOBUS_SH_SED-sed} -e "s/subject=[ ]*//"` 
        # find signed cert
        for p in ${GRID_CA_DIR}/newcerts/*.pem; do
            subj_tmp_output=/tmp/tmp_output.$$
            ${openssl_cmd} x509 -noout -subject -in ${p} \
                               > ${subj_tmp_output} 2>&1
            res=$?
            if test $res != 0; then
                echo ""
                echo "ERROR: Failed to get subject of signed cert at: ${p}"
                echo ""
            fi

            signed_subj=`cat ${subj_tmp_output} | ${GLOBUS_SH_SED-sed} -e "s/subject=[ ]*//"`

            if test "${signed_subj}" = "${req_subj}"; then
                SIGNED_CERT=${p}
            fi
        done

        if test -z "${SIGNED_CERT}"; then
            echo ""
            echo "ERROR: Failed to find signed cert in CA cert store with subject:"
            echo "       ${req_subj}"
            echo ""
            do_cleanup
            exit 1
        fi

        if test ! -f "${SIGNED_CERT}"; then
            echo ""
            echo "ERROR: Could not find cert file to revoke in certificate store:"
            echo "       ${SIGNED_CERT}"
            echo ""
            do_cleanup
            exit 1
        fi

        SIGNED_SUBJECT="${req_subj}"
        exp_date=`${openssl_cmd} x509 -in ${SIGNED_CERT} -noout -enddate | \
                         ${GLOBUS_SH_SED-sed} -e "s|notAfter=[ ]*||"`
        expired=`check_expired ${exp_date}`
        if test -n "${force_sign}" || test "${expired}" == "0"; then

            echo ""
            echo "Revoking previous certificate"

            tmp_revoke_output=/tmp/tmp_revoke_out.$$

            do_password_input "To revoke the current certificate"
            ${openssl_cmd} ca $openssl_options -batch -config ${grid_ca_conf} \
                    -revoke ${SIGNED_CERT} \
                    2> ${tmp_revoke_output}
	    res=$?
	    end_password_input
            if test $res != 0; then
                echo ""
	        echo "ERROR: Failed to revoke previous certificate with subject:"
		echo "       ${SIGNED_SUBJECT}"
                echo ""
    		echo "========== ERROR MESSAGES FROM OPENSSL =========="
    		cat ${tmp_revoke_output} 1>&2
    		echo "================================================="
	        echo ""
                ${GLOBUS_SH_RM-rm} -f ${tmp_revoke_output}
                do_cleanup
                exit 1
            else
                
                ${GLOBUS_SH_RM-rm} -f ${tmp_revoke_output}
                echo ""
                echo "Signing new certificate"
                do_sign;
                return;
            fi

        else
            echo ""
            echo "There is already a valid certificate that matches this subject at:"
            echo
            echo "${SIGNED_CERT}"
            echo
            echo "You can use the -force option to overwrite"
            echo "this certificate and create a new one."
            echo ""

            ${GLOBUS_SH_RM-rm} -f ${subj_tmp_output}
            
            do_cleanup
            exit 1
        fi
    fi

    echo ""
    echo "ERROR running command:"
    echo ""
    echo " ${openssl_cmd} ca $openssl_options \\"
    echo "    -batch -config ${grid_ca_conf} \\"
    echo "    -in ${TMP_REQ_FILE} -out ${TMP_CERT_FILE}"
    echo ""
    echo "========== ERROR MESSAGES FROM OPENSSL =========="
    cat ${tmp_output} 1>&2
    echo "================================================="

    # check if the error was with 
    no_config_file=`${GLOBUS_SH_GREP-grep} "error loading the config file" ${tmp_output}`
    if test -n "${no_config_file}"; then

        echo ""
        echo "ERROR: No CA config file found."
        echo "Either simple CA setup package is not installed,"
        echo "or the config file is not located at:"
        echo ""
        echo "  ${grid_ca_conf}"
        echo ""
    fi

    # check if the CA's private key could be loaded
    wrong_password=`${GLOBUS_SH_GREP-grep} "unable to load CA private key" ${tmp_output}`
    if test -n "${wrong_password}"; then
    
        echo ""
        echo "ERROR: The CA private key could not be loaded."
        echo "Possibly an incorrect password for the CA key was used."
        echo ""
    fi

    # check that the cert request matches the CA cert
    wrong_org=`${GLOBUS_SH_GREP-grep} "field needed to be the same" ${tmp_output}`
    if test -n "${wrong_org}"; then
    
        echo "" 
        echo "ERROR: The cert request does not match CA cert"
        echo "Check that the correct security config files are"
        echo "set during grid-cert-request"
        echo ""
        echo "The default configuration can be set using either"
        echo "the command:  grid-default-ca, or via the -ca option"
        echo "to grid-cert-request."
        echo ""
    fi

    ${GLOBUS_SH_RM-rm} -f ${tmp_output}

    echo ""
    do_cleanup
    exit 1
fi

}

readCommandLine "$@"

if test -z "$GRID_CA_DIR"; then
    GRID_CA_DIR=${HOME}/.globus/simpleCA/
fi

if test ! -d ${GRID_CA_DIR}; then
    echo ""
    echo "ERROR: No simple CA directory"
    echo "found at ${GRID_CA_DIR}"
    echo "Either specify a directory with -dir, or run"
    echo "setup-simple-ca to create a CA"
    echo ""
    exit 1
fi

if test ! -f ${GRID_CA_DIR}/cacert.pem; then
    echo ""
    echo "ERROR: No simple CA setup found at ${GRID_CA_DIR}."
    echo "The CA certificate is missing!"
    echo "Please run setup-simple-ca before"
    echo "signing certificates."
    echo ""
    exit 1
fi

grid_ca_conf=${GRID_CA_DIR}/grid-ca-ssl.conf
openssl_cmd=${GLOBUS_LOCATION}/bin/openssl

TMP_REQ_FILE=/tmp/tmp_cert_req.pem.$$
TMP_CERT_FILE=/tmp/tmp_cert.pem.$$

${GLOBUS_SH_CP-cp} ${INPUT_REQ_FILE} ${TMP_REQ_FILE}

echo ${openssl_options} | grep "\-passin" > /dev/null
res1=$?
if test ! $res1 = 0; then
    echo ${openssl_options} | grep "\-key" > /dev/null
    res1=$?
fi

if test ! $res1 = 0; then
    need_password_input=1
    openssl_options="${openssl_options} -passin stdin"
fi

do_sign;

if test ! -f ${TMP_CERT_FILE}; then
	echo "ERROR: ${TMP_CERT_FILE} does not exist.  Invalid internal state, exiting..."
	echo ""
	exit 1
fi

${openssl_cmd} x509 -in ${TMP_CERT_FILE} -noout -serial > /dev/null 2>&1
res=$?
if test $res != 0; then
	echo ""
	echo "ERROR: Failed to get serial number of newly signed cert at: ${TMP_CERT_FILE}"
	echo ""
fi

NEW_SERIAL=`${openssl_cmd} x509 -in ${TMP_CERT_FILE} -noout -serial | ${GLOBUS_SH_SED-sed} -e "s|serial=||"`

echo ""
echo "The new signed certificate is at: ${GRID_CA_DIR}/newcerts/${NEW_SERIAL}.pem"
echo ""

CERT_OUTPUT_DIR=`dirname ${SIGNED_OUTPUT_FILE}`
if test -w "${CERT_OUTPUT_DIR}"; then
    ${GLOBUS_SH_CP-cp} ${TMP_CERT_FILE} ${SIGNED_OUTPUT_FILE}
else
    echo ""
    echo "ERROR: Cannot create the requested output certificate file"
    echo "   ${SIGNED_OUTPUT_FILE}"
    echo "Instead manually copy and rename the new signed certificate at"
    echo "   ${GRID_CA_DIR}/newcerts/${NEW_SERIAL}.pem"
    echo ""
fi

do_cleanup
exit
