#! /bin/sh 

# 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
}

my_mkdir() {

    ${GLOBUS_SH_MKDIR-mkdir} ${1}
    res=$?
    if test $? -ne 0; then
        echo ""
        echo "ERROR: Failed to make directory: ${1}"
        echo "Check permissions of base dir"
        echo ""
        exit 1
    fi
}

check_file() {
    if test ! -f $1; then
        echo ""
        echo "ERROR: Problem with install: $1 does not exist!"
        echo "Please report this error to discuss@globus.org"
        echo ""
        exit 1
    fi
}

############################################################
# grid-ca-setup: Set up the CA configuration
############################################################

############################################################
# make_template_ca_setup: untars the template of the ca
#                         setup package into a tmp directory
############################################################
make_template_ca_setup() {

    template_package_dir=${GLOBUS_LOCATION}/setup/globus/
    template_package_file=${template_package_dir}/globus_simple_ca_setup_template.tar.gz
    tmp_ca_setup_dir=${GLOBUS_SH_TMP-/tmp/}/${USER}_tmp_ca_setup
    ${GLOBUS_SH_MKDIR-mkdir} ${tmp_ca_setup_dir}
    if test $? -ne 0; then
        echo ""
        echo "Failed to create directory: ${tmp_ca_setup_dir}."
        echo "Do you have write permissions to /tmp?"
        echo ""
        exit 1
    fi

    current_dir=${PWD}
    cd ${tmp_ca_setup_dir}
    if test $? -ne 0; then
        echo ""
        echo "Failed to access directory ${tmp_ca_setup_dir}"
        echo ""
        exit 1
    fi
    
    ${GLOBUS_SH_GZIP-gzip} -dc ${template_package_file} | ${GLOBUS_SH_TAR-tar} xf -
    if test $? -ne 0; then
        echo ""
        echo "Failed to extract tarball: ${template_package_file}"
        echo "to location ${tmp_ca_setup_dir}"
        echo ""
        exit 1
    fi

    grid_security_conf_template=${tmp_ca_setup_dir}/grid-security.conf.tmpl
    check_file ${grid_security_conf_template}

    ca_signing_policy_conf_template=${tmp_ca_setup_dir}/ca-signing-policy.conf.tmpl
    check_file ${ca_signing_policy_conf_template}

    ssl_conf_template=${tmp_ca_setup_dir}/globus-ssl.conf.tmpl
    check_file ${ssl_conf_template}
}

############################################################
# create_ca_directory: asks the user for the CA dir path
#                      and sets up the appropriate files
############################################################
create_ca_directory() {

${GLOBUS_SH_CAT-cat} <<EOF
 

    C e r t i f i c a t e    A u t h o r i t y    S e t u p

This script will setup a Certificate Authority for signing Globus
users certificates.  It will also generate a simple CA package
that can be distributed to the users of the CA.

The CA information about the certificates it distributes will
be kept in:

${GRID_CA_DIR}
EOF

grid_ca_conf=${GRID_CA_DIR}/grid-ca-ssl.conf

if test -d "${GRID_CA_DIR}"; then

    if test -z "${force}"; then
        echo ""
        echo "ERROR: It looks like a CA has already been setup at this location."
        recho "Do you want to overwrite this CA? (y/n) [n]: "
        read tmp_answer
        overwrite_answer=${tmp_answer:-n}
        if test ! `echo ${overwrite_answer} | ${GLOBUS_SH_TR-tr} 'A-Z' 'a-z' | ${GLOBUS_SH_CUT-cut} -c1` = 'y'; then
            exit 1;
        fi
    fi
else
    if test ! -d "${HOME}/.globus" && test -n "${default_loc}"; then
	${GLOBUS_SH_MKDIR-mkdir} ${HOME}/.globus
        if test $? -ne 0; then
            echo "ERROR: Couldn't create directory: ${HOME}/.globus/"
            echo "       make sure you have valid permissions set."
            exit 1;
        fi
    fi
    ${GLOBUS_SH_MKDIR-mkdir} ${GRID_CA_DIR}
    if test $? -ne 0; then
        echo "ERROR: Couldn't create directory: ${GRID_CA_DIR}"
        echo "       make sure you have valid permissions set."
        exit 1;
    fi
fi

CA_KEY_FILE=${GRID_CA_DIR}/private/cakey.pem
CA_CERT_FILE=${GRID_CA_DIR}/cacert.pem

${GLOBUS_SH_RM-rm} -rf ${GRID_CA_DIR}

# from the CA.sh script - setup the CA directory 
my_mkdir ${GRID_CA_DIR}
my_mkdir ${GRID_CA_DIR}/certs/
my_mkdir ${GRID_CA_DIR}/crl/
my_mkdir ${GRID_CA_DIR}/newcerts/
my_mkdir ${GRID_CA_DIR}/private/

echo "01" > ${GRID_CA_DIR}/serial
if test $? -ne 0; then
    echo ""
    echo "ERROR: Could not write to ${GRID_CA_DIR}/serial"
    echo "Check permissions on the dir"
    echo ""
    exit 1
fi

touch ${GRID_CA_DIR}/index.txt
if test $? -ne 0; then
    echo ""
    echo "ERROR: Could not write to ${GRID_CA_DIR}/index.txt"
    echo "Check the permissions on the dir"
    echo ""
    exit 1
fi

# sets the permissions of the CA directory
${GLOBUS_SH_CHMOD-chmod} ${CA_DIR_PERMS}  \
${GRID_CA_DIR}                            \
${GRID_CA_DIR}/certs/                     \
${GRID_CA_DIR}/crl/                       \
${GRID_CA_DIR}/newcerts/                  \
${GRID_CA_DIR}/private/                   \
${GRID_CA_DIR}/serial                     \
${GRID_CA_DIR}/index.txt

if test $? -ne 0; then
    echo ""
    echo "ERROR: Failed to chmod files in ${CA_DIR_PERMS}"
    echo ""
    exit 1
fi

}

############################################################
# generate_unique_name: finds a unique name for the CA
#                       based on the hostname
############################################################
generate_unique_name() {

tmp_hostname=`${GLOBUS_LOCATION}/bin/globus-hostname`

if test -z "${tmp_hostname}"; then
    echo "" 
    echo "The hostname of this machine is not set.  Set the"
    echo "hostname before running this script."
    echo ""
    exit 1
fi

echo "simpleCA-${tmp_hostname}"
return 0
}

split_subject() {

    casubject="${1}"

    GSI_CA_NAME=`echo ${casubject} | ${GLOBUS_SH_SED-sed} -e "s/[Cc][Nn]=\([^,]*\),.*/\1/"`
    GSI_CA_BASE_DN=`echo ${casubject} | ${GLOBUS_SH_SED-sed} -e "s/[Cc][Nn]=[^,]*,\(.*\)/\1/"`
    HAS_GLOBUS_NS=`echo ${GSI_CA_BASE_DN} | ${GLOBUS_SH_SED-sed} -e "s/.*\([Oo]=[Gg][Ll][Oo][Bb][Uu][Ss],[ ]*[Oo]=[Gg][Rr][Ii][Dd]\)/\1/"` 
    check_for_globus_ns "$GSI_CA_BASE_DN"
    if test -z "${GSI_CA_NAME}" || 
        test -z "${GSI_CA_BASE_DN}"; then
        echo "" 
        echo "The subject: ${casubject} is not a valid subject name"
        echo "Use the default subject name if you don't know the correct"
        echo "format to use"
        return 1
    elif test "`check_for_globus_ns "$GSI_CA_BASE_DN"`" = "YES"; then
        echo ""
        echo "ERROR: The Globus namespace (o=Globus, o=Grid) is restricted."
        echo "Please use a different namespace."
        
        GSI_CA_BASE_DN="ou=${CA_ORG_NAME}, ou=GlobusTest, o=Grid"
        GSI_CA_NAME="Globus Simple CA"
        return 1
    else
        return 0
    fi
}

############################################################
# get_ca_info: gets the CA information from the user to 
#              create the CA certificate
############################################################
get_ca_info() {


CA_ORG_NAME=`generate_unique_name`
res=$?
if test $res -ne 0; then
    exit 1
fi
GSI_CA_BASE_DN="ou=${CA_ORG_NAME}, ou=GlobusTest, o=Grid"
GSI_CA_NAME="Globus Simple CA"

got_subject=""

while test -z "${got_subject}" ; do

    casubject="cn=${GSI_CA_NAME}, ${GSI_CA_BASE_DN}"
    if test -n "${request_subject}"; then
        casubject="${request_subject}"
    fi
	
    echo ""
    echo "The unique subject name for this CA is:"
    echo ""
    echo "${casubject}"
    echo ""

    if test -n "${noint}" || test -n "${request_subject}"; then
        split_subject "${request_subject:-${casubject}}"
        if test $? -eq 0; then
            got_subject="yes"
        else
            exit 1
        fi
    else

        recho "Do you want to keep this as the CA subject (y/n) [y]: "
        
        read _answer
        answer=${_answer:-y}
        first_char_answer="`echo ${answer} | ${GLOBUS_SH_TR-tr} 'A-Z' 'a-z' | ${GLOBUS_SH_CUT-cut} -c1`";
        
        if test "${first_char_answer}" = "n"; then
            
            echo ""
            recho "Enter a unique subject name for this CA: "
            read casubject
            echo ""
            if test -n "${casubject}"; then
                split_subject "${casubject}"
                if test $? -eq 0; then
                    got_subject="yes"
                fi
            fi
        elif test "${first_char_answer}" = "y"; then
            got_subject="yes"
        else
            echo ""
            echo "Please answer 'y' or 'n'"
            echo ""
        fi
    fi
done

get_ca_email=""

if test -n "${request_email}" || test -n "${noint}"; then
    GSI_CA_EMAIL_ADDR=${request_email}
    get_ca_email="done"
fi

while test -z "${get_ca_email}"; do

    echo ""
    echo "Enter the email of the CA (this is the email where certificate"
    recho "requests will be sent to be signed by the CA): "
    read GSI_CA_EMAIL_ADDR
    if test -n ${GSI_CA_EMAIL_ADDR}; then
	get_ca_email="done"
    fi
done


if test -n "${request_days}"; then
    CA_CERT_DAYS=${request_days}
elif test -z "${noint}"; then

${GLOBUS_SH_CAT-cat}  <<EOF

The CA certificate has an expiration date. Keep in mind that 
once the CA certificate has expired, all the certificates 
signed by that CA become invalid.  A CA should regenerate 
the CA certificate and start re-issuing ca-setup packages 
before the actual CA certificate expires.  This can be done 
by re-running this setup script.  Enter the number of DAYS 
the CA certificate should last before it expires.
EOF

recho "[default: 5 years (1825 days)]: "
read _CA_CERT_DAYS
CA_CERT_DAYS=${_CA_CERT_DAYS:-${CA_CERT_DAYS}}
echo

fi

return
}

############################################################
# env_replace: replace environment variables from a 
#              file (grid-security.conf) with values
#              determined from this script
############################################################
env_replace () {
   _env="$2"
   _prefix="$1"
   eval _value="\${$_env}"
   ${GLOBUS_SH_SED-sed} -e "s|^${_prefix}_${_env}=.*|${_prefix}_${_env}=\"$_value\"|"
}

############################################################
# save_ca_settings: save the settings determined from this
#                   script to files (grid-security.conf &
#                   grid-ca-ssl.cnf)
############################################################
save_ca_settings() {

    GSI_USER_BASE_DN="ou=\${_domain}, ${GSI_CA_BASE_DN}"
    GSI_HOST_BASE_DN=${GSI_CA_BASE_DN}
    
#    echo `cat ${security_conf_file} | env_replace SETUP GSI_CA_BASE_DN`
    ${GLOBUS_SH_CAT-cat} ${grid_security_conf_template}  |\
    env_replace SETUP   GSI_CA_BASE_DN    |\
    env_replace SETUP   GSI_CA_NAME       |\
    env_replace SETUP   GSI_CA_EMAIL_ADDR |\
    env_replace DEFAULT GSI_CA_BASE_DN    |\
    env_replace DEFAULT GSI_CA_NAME       |\
    env_replace DEFAULT GSI_CA_EMAIL_ADDR |\
    env_replace DEFAULT GSI_HOST_BASE_DN  |\
    env_replace DEFAULT GSI_USER_BASE_DN  > ${grid_security_conf_template}.1

    if test $? -ne 0; then
        echo ""
        echo "ERROR: Failed to modify file ${grid_security_conf_template}"
        echo "Check that the file exists and permissions are valid"
        echo ""
        exit 1
    fi

    ${GLOBUS_SH_MV-mv} ${grid_security_conf_template}.1 ${grid_security_conf_template}
}

############################################################
# check_for_globus_ns: determine if the user specified subject
#                      contians the globus namespace
############################################################
check_for_globus_ns() {
    echo "$1" | ${GLOBUS_SH_AWK-awk} '
BEGIN     { FS = ","; lastorg=0; lastou=0; hasgrid=0; }

{
    split($0, b, ",");
    i=1;
    while(b[i] != "")
    {
        split(b[i],c,"=");
        if(tolower(c[1]) ~ /o/)
        {
	    org[++lastorg]=c[2];	    
        }
        i++;
    }
}

END {
    for(i = lastorg; i > 0; i--)
    {
        if(tolower(org[i]) == "grid")
        {
            hasgrid=i;
        }
        
        if(tolower(org[i]) == "globus" && hasgrid == (i + 1))
        {
            print "YES";
        }
   }
}
'
}

############################################################
# ldap_dn_to_ssl_dn: create the entries in the grid-ca-ssl.cnf
#                    file from values determined from this
#                    script
############################################################
ldap_dn_to_ssl_dn() {
    echo "$1" | ${GLOBUS_SH_AWK-awk} '
BEGIN     { FS = ","; lastorg=0; lastou=0; } 

{ 
    split($0, b, ",");
    i=1;
    while(b[i] != "")
    {
        split(b[i],c,"=");
        if(tolower(c[1]) ~ /ou/)
        { 
            ou[lastou++]=c[2];
        }
        else if(tolower(c[1]) ~ /c/)
        {
            country=c[2];
        }
        else if(tolower(c[1]) ~ /o/)
        {
            org[lastorg++]=c[2];
        }
        i++;
    }
}

END {
    if(country) {
        print  "countryName                     = Country Name (2 letter code)";
        printf("countryName_default             = %s\n",country);
        print  "countryName_min                 = 2";
        print  "countryName_max                 = 2";
    }

    for(i = lastorg; i > 0; i--)
    {
        printf("%d.organizationName               = Level %d Organization\n",lastorg-i,lastorg-i);
        printf("%d.organizationName_default       = %s\n", lastorg-i, org[i-1]);
    }
    for(i = lastou; i > 0; i--)
    {
        printf("%d.organizationalUnitName          = Level %d Organizational Unit\n",lastou-i,lastou-i);
        printf("%d.organizationalUnitName_default = %s\n", lastou-i, ou[i-1]);
    }

    print      "commonName                      = Name (e.g., John M. Smith)";
    print      "commonName_max                  = 64";
}
'
}

############################################################
# create_input_file: generate the input file to be passed as
#                    stdin to the openssl req utility.
############################################################
create_input_file () {
  _common_name="$1"
  _config_file="$2"

# Parse the ssleay configuration file, to determine the
# correct default 

${GLOBUS_SH_AWK-awk}  < $_config_file '
 
  /^\[ req_distinguished_name \]/ {
     start_parsing=1;
     next;
  }

  /^\[ .*/ {
     start_parsing=0;
     next;
  }

  /^[a-zA-Z0-9\.]*_default[ \t]*=/ && start_parsing==1 {
     split($0, a, "=");
     # default value is in a[2], but we should strip of leading ws
     for(i=1;substr(a[2],i,1) == " " || substr(a[2],i,1) == "\t"; i++);
     print substr(a[2], i);
     next;
}
'

   echo ${_common_name}
}

############################################################
# generate_ca_certificate: the meat & potatoes - calls the 
#                          openssl req utility that creates
#                          the CA certificate
############################################################
generate_ca_certificate() {

generatecadir=/tmp/generate_ca_certification.$RANDOM.$$
(umask 077 && mkdir ${generatecadir}) || {
    echo "Could not create temporary directory! Exiting." 1>&2
    exit 1
}

check_file ${grid_security_conf_template}

. ${grid_security_conf_template}

ca_ssl_conf_template=${tmp_ca_setup_dir}/grid-ca-ssl.conf.tmpl

tmp_ca_conf=$generatecadir/tmp_ssl.conf.1.$$

${GLOBUS_SH_SED-sed} -e "1,/BEGIN CONFIG/p" -e d \
		     < $ca_ssl_conf_template > $tmp_ca_conf
if test $? -ne 0; then
    echo ""
    echo "ERROR: Failed to write to ${tmp_ca_conf}"
    echo ""
    exit 1
fi

${GLOBUS_SH_SED-sed} -e "s|^dir\([^=]*\)=.*$|dir\1= ${GRID_CA_DIR}|" \
		     < $tmp_ca_conf > $grid_ca_conf
if test $? -ne 0; then
    echo ""
    echo "ERROR: Failed to write to ${grid_ca_conf}"
    echo ""
    exit 1
fi

${GLOBUS_SH_RM-rm} -f ${tmp_ca_conf}

ldap_dn_to_ssl_dn "${GSI_CA_BASE_DN}" >> $grid_ca_conf
${GLOBUS_SH_SED-sed} -e "/END CONFIG/,\$p" -e d < $ca_ssl_conf_template >> $grid_ca_conf

if test $? -ne 0; then
    echo ""
    echo "ERROR: Failed to write to ${grid_ca_conf}"
    echo ""
    exit 1
fi

CA_REQ_INPUT=${generatecadir}/tmp_openssl_input.conf.1.$$

create_input_file "${GSI_CA_NAME}" "${grid_ca_conf}" > ${CA_REQ_INPUT}
check_file ${CA_REQ_INPUT}

if test -n "${request_password}"; then
    password_option="-passout pass:${request_password} "
elif test -n "${noint}"; then
    password_option="-passout pass:globus "
else
    password_option=""
fi

# create CA certificate

if test -n "${verbose}"; then
    ${openssl_cmd} req ${openssl_options} ${password_option} -config "${grid_ca_conf}" \
        -x509 -days ${CA_CERT_DAYS} \
        -newkey rsa:1024 -keyout ${CA_KEY_FILE} \
        -out ${CA_CERT_FILE} < ${CA_REQ_INPUT}
    RET=$?
else
# create CA certificate request
    ${openssl_cmd} req ${openssl_options} ${password_option} -config "${grid_ca_conf}" \
        -x509 -days ${CA_CERT_DAYS} \
        -newkey rsa:1024 -keyout ${CA_KEY_FILE} \
        -out ${CA_CERT_FILE} < ${CA_REQ_INPUT} > openssl_req.log 2>&1
    RET=$?
fi


${GLOBUS_SH_RM-rm} -rf ${generatecadir}

if test ${RET} -eq 0; then
    ${GLOBUS_SH_CLEAR-clear}
else
    echo "Error number ${RET} was returned by " 1>&2
    echo "   ${openssl_cmd}"
    exit ${RET}
fi

}


###########################################################
# emit_directions: Provide instructions to the end user
###########################################################
emit_directions () {

${GLOBUS_SH_CAT-cat} <<EOF

A self-signed certificate has been generated 
for the Certificate Authority with the subject: 

${CA_CERT_SUBJECT}

If this is invalid, rerun this script 

$0

and enter the appropriate fields.

-------------------------------------------------------------------

The private key of the CA is stored in ${CA_KEY_FILE}
The public CA certificate is stored in ${CA_CERT_FILE}

The distribution package built for this CA is stored in

${GRID_CA_DIR}/${CA_UTILS_PACKAGE}

This file must be distributed to any host wishing to request
certificates from this CA.

CA setup complete.

EOF

if test -z "${nobuild}"; then

${GLOBUS_SH_CAT-cat} <<EOF
The following commands will now be run to setup the security
configuration files for this CA:

\$GLOBUS_LOCATION/sbin/gpt-build ${GRID_CA_DIR}/${CA_UTILS_PACKAGE}

\$GLOBUS_LOCATION/sbin/gpt-postinstall
EOF

fi

${GLOBUS_SH_CAT-cat} <<EOF
-------------------------------------------------------------------


EOF

}

############################################################
# install_security_config: run globus-build on the security
#                          configuration package associated
#                          with the CA
#
############################################################
install_security_config() {

    cd ${current_dir}

    if [ -f ${GPT_LOCATION}/sbin/gpt-build ]; then
	buildcmd=${GPT_LOCATION}/sbin/gpt-build
    elif [ -f ${GPT_LOCATION}/sbin/globus-build ]; then
	buildcmd=${GPT_LOCATION}/sbin/globus-build
    elif [ -f ${GLOBUS_LOCATION}/sbin/gpt-build ]; then
	buildcmd=${GLOBUS_LOCATION}/sbin/gpt-build
    elif [ -f ${GLOBUS_LOCATION}/sbin/globus-build ]; then
	buildcmd=${GLOBUS_LOCATION}/sbin/globus-build
    fi

    if test -n "$verbose"; then
        ${buildcmd} -force ${GRID_CA_DIR}/${CA_UTILS_PACKAGE}
    else
        ${buildcmd} -force ${GRID_CA_DIR}/${CA_UTILS_PACKAGE} > build.log 2>&1
    fi
    
    
    if [ ! $? -eq 0 ]; then
	echo "ERROR:  could not run build command: ${buildcmd} -force ${GRID_CA_DIR}/${CA_UTILS_PACKAGE}"
	exit 1;
    fi

    SIMPLE_CA_SETUP_TMP_WORKING_DIR=$PWD
    cd ${GLOBUS_LOCATION}/setup/globus/
    ./setup-ssl-utils.${CA_CERT_HASH}
    cd $SIMPLE_CA_SETUP_TMP_WORKING_DIR
}

################################################################
# finish_simple_ca_setup: close out the meta-data gpt packaging
#                         of the simple_ca_setup package.
#                         This prevents the setup-simple-ca
#                         script from getting run repeatedly.
################################################################
finish_simple_ca_setup() {

    ${GLOBUS_SH_PERL-perl} -I${GPT_LOCATION}/lib/perl -I${GLOBUS_LOCATION}/lib/perl -e " \
\
use Getopt::Long; \
use English; \
\
require Grid::GPT::Setup; \
my \$metadata = new Grid::GPT::Setup(package_name => \"simple_ca_setup\"); \
\$metadata->finish();"

}

############################################################
# generate_setup_gsi: modify the setup-gsi.pl template to
#                     have the appropriate values for this
#                     CA
############################################################
generate_setup_file() {

    file_pre=$1
    ${GLOBUS_SH_SED-sed} -e "s|__CACERT_HASH__|${CA_CERT_HASH}|g" \
			 "${tmp_ca_setup_dir}/${file_pre}.tmpl" \
      > "${tmp_ca_setup_dir}/${file_pre}"
    check_file ${tmp_ca_setup_dir}/${file_pre}
}

############################################################
# copy_unchanged_file: copies files to the tarball directory
#                       which do not need modification
############################################################
copy_unchanged_file() {

    ${GLOBUS_SH_CP-cp} "${tmp_ca_setup_dir}/$1" "${tmp_simple_ca_dir}/$1"
}

############################################################
# generate_utils_package: create the CA config package
#                         that gets distributed to the
#                         users of this CA.
############################################################
generate_utils_package() {

CA_CERT_HASH=`${openssl_cmd} x509 -hash -noout -in ${CA_CERT_FILE}`

# creating <HASH>.0
${GLOBUS_SH_CAT-cat} ${CA_CERT_FILE} > ${tmp_ca_setup_dir}/${CA_CERT_HASH}.0
check_file "${CA_CERT_HASH}.0"

# creating <HASH>.signing_policy file
CA_CERT_SUBJECT="`${openssl_cmd} x509 -text -noout -in ${CA_CERT_FILE} |\
		    ${GLOBUS_SH_GREP-grep} 'Subject:' | ${GLOBUS_SH_AWK-awk} -F: '{print $2}' |\
		    ${GLOBUS_SH_CUT-cut} -c2-`"
CA_CERT_SUBJECT=`echo "/${CA_CERT_SUBJECT}" | ${GLOBUS_SH_SED-sed} -e 's|, |/|g'`

CA_COND_SUBJECT=`echo ${CA_CERT_SUBJECT} | ${GLOBUS_SH_SED-sed} -e "s/CN=.*/\*/"`

${GLOBUS_SH_SED-sed} -e "s|CA_SUBJECT_NAME|${CA_CERT_SUBJECT}|" \
		     -e "s|CA_HASH|${CA_CERT_HASH}|" \
		     -e "s|CA_SIGNING_POLICY|${CA_COND_SUBJECT}|" \
		     ${ca_signing_policy_conf_template} > ${tmp_ca_setup_dir}/${CA_CERT_HASH}.signing_policy
check_file "${CA_CERT_HASH}.signing_policy"

# creating grid-security.conf.HASH
${GLOBUS_SH_CP-cp} ${grid_security_conf_template} ${tmp_ca_setup_dir}/grid-security.conf.${CA_CERT_HASH}
check_file ${tmp_ca_setup_dir}/grid-security.conf.${CA_CERT_HASH}

# creating files that need HASH of ca cert
generate_setup_file "setup-gsi.pl"
generate_setup_file "setup-gsi"
generate_setup_file "grid-security-config.in"
generate_setup_file "grid-cert-request-config.in"
generate_setup_file "Makefile.am"
generate_setup_file "Makefile.in"
generate_setup_file "setup-ssl-utils.pl"
generate_setup_file "/pkgdata/pkg_data_src.gpt.in"
generate_setup_file "setup-ssl-utils"
generate_setup_file "setup-ssl-utils.__CACERT_HASH__"
${GLOBUS_SH_CP-cp} "${tmp_ca_setup_dir}/globus-ssl.conf.tmpl" "${tmp_ca_setup_dir}/globus-ssl.conf"
check_file "${tmp_ca_setup_dir}/globus-ssl.conf"

${GLOBUS_SH_CP-cp} "${tmp_ca_setup_dir}/setup-ssl-utils.__CACERT_HASH__" "${tmp_ca_setup_dir}/setup-ssl-utils.${CA_CERT_HASH}"
check_file "${tmp_ca_setup_dir}/setup-ssl-utils.${CA_CERT_HASH}"

echo ""
recho "creating CA config package..."

cd ${tmp_ca_setup_dir}
if test $? -ne 0; then
    echo ""
    echo "ERROR: Failed to change working directory to: ${tmp_ca_setup_dir}"
    echo ""
    exit 1
fi

#${GLOBUS_SH_CHMOD-chmod} 0700 bootstrap
${GLOBUS_SH_CHMOD-chmod} 0700 configure

CA_UTILS_PACKAGE_DIR=globus_simple_ca_${CA_CERT_HASH}_setup-0.19
CA_UTILS_PACKAGE=$CA_UTILS_PACKAGE_DIR.tar.gz

#./bootstrap

if test -n "$verbose"; then
    export GLOBUS_LOCATION=${GLOBUS_LOCATION};cd ${tmp_ca_setup_dir};./configure $outlog
    RES=$?
else
    export GLOBUS_LOCATION=${GLOBUS_LOCATION};cd ${tmp_ca_setup_dir};./configure $outlog > configure.log 2>&1
    RES=$?
fi

if test $RES -ne 0; then
    echo ""
    echo "ERROR: Unable to configure the simple_ca ${CA_CERT_HASH} setup package"
    echo ""
    exit 1
fi

if test -n "$verbose"; then
    export GLOBUS_LOCATION=${GLOBUS_LOCATION};cd ${tmp_ca_setup_dir};make distdir
    RES=$?
else
    export GLOBUS_LOCATION=${GLOBUS_LOCATION};cd ${tmp_ca_setup_dir};make distdir > make.log 2>&1
    RES=$?
fi

if test $RES -ne 0; then
    echo ""
    echo "ERROR: Unable to create simple_ca ${CA_CERT_HASH} setup package distribution directory"
    echo ""
    exit 1
fi

cd ${tmp_ca_setup_dir}
if test $? -ne 0; then
    echo ""
    echo "ERROR: Failed to change working directory to: ${tmp_ca_setup_dir}"
    echo ""
    exit 1
fi

${GLOBUS_SH_CHMOD-chmod} -R a+r ${CA_UTILS_PACKAGE_DIR}
RES=$?
if test $RES -ne 0; then
    echo ""
    echo "ERROR: Unable to chmod ${CA_UTILS_PACKAGE_DIR}"
    echo ""
    exit 1
fi

if test -n "$verbose"; then
    ${GLOBUS_SH_TAR-tar} cvf $CA_UTILS_PACKAGE_DIR.tar $CA_UTILS_PACKAGE_DIR
    RES=$?
else
    ${GLOBUS_SH_TAR-tar} cvf $CA_UTILS_PACKAGE_DIR.tar $CA_UTILS_PACKAGE_DIR > tar.log 2>&1
    RES=$?
fi

if test $RES -ne 0; then 
	echo ""
	echo "SETUP FAILED: Could not create tarball of setup package."
	echo ""
	exit 1;
fi


if test -n "$verbose"; then
    ${GLOBUS_SH_GZIP-gzip} -f9 $CA_UTILS_PACKAGE_DIR.tar
    RES=$?
else
    ${GLOBUS_SH_GZIP-gzip} -f9 $CA_UTILS_PACKAGE_DIR.tar > gzip.log 2>&1
    RES=$?
fi

if test $RES -ne 0; then
	echo ""
	echo "SETUP FAILED: Could not create gzip of setup package."
	echo ""
	exit 1;
fi

if test ! -f ${tmp_ca_setup_dir}/${CA_UTILS_PACKAGE}; then
    echo ""
    echo "Creation of  the CA setup package: ${CA_UTILS_PCKAGE} failed."
    echo ""
    exit 1;
fi

# versions of this generated package should not be changed without changing the package metadata as well.
${GLOBUS_SH_CP-cp} ${tmp_ca_setup_dir}/${CA_UTILS_PACKAGE} ${GRID_CA_DIR}/${CA_UTILS_PACKAGE}

${GLOBUS_SH_RM-rm} -rf ${tmp_ca_setup_dir}

echo "done."
echo

}

############################################################
# do_trap:  catches any abortive signals and does cleanup
############################################################
do_trap() {

    echo ""
    echo ""
    echo "Normal program execution interrupted.  You will"
    echo "need to rerun the script:"
    echo ""
    echo "\${GLOBUS_LOCATION}/setup/globus/setup-simple-ca"
    echo ""
    echo "to setup the simple CA."
    echo ""

    ${GLOBUS_SH_RM-rm} -rf ${tmp_ca_setup_dir}
    if test -d "${generatecadir}"; then
        ${GLOBUS_SH_RM-rm} -rf "${generatecadir}"
    fi
    cd ${current_dir}
    
    exit 1
}


############################################################
# main code section
############################################################

currentwd=${PWD}
if test -z "${currentwd}"; then
    currentwd=`cwd`
    if test -z "${currentwd}"; then
        echo ""
        echo "ERROR: Failed to get current working directory"
	echo ""
	exit 1
    fi
fi

thiscommand=${0}
currenthome=${HOME}
mycommand=

##  expand . and ~
firstchar=`echo ${thiscommand} | cut -b 1`
if test "${firstchar}" = "."; then
    rest=`echo ${thiscommand} | cut -b 2-`
    mycommand="${currentwd}/${rest}"
elif test "${firstchar}" = "~"; then
    rest=`echo "${thiscommand}" | cut -b 2-`
    mycommand="${currenthome}/${rest}"
elif test "${firstchar}" = "/"; then
    mycommand="${thiscommand}"
else
    mycommand="${currentwd}/${rest}"
fi

if test ! -x ${mycommand}; then
   echo ""
   echo "ERROR: Failed to parse ${mycommand} into a the path for this script"
   echo ""
   exit 1
fi

if test -z "${GLOBUS_LOCATION}"; then
    
    GLOBUS_LOCATION=`echo ${mycommand} | sed -e "s|\(.*\)/setup/globus/setup-simple-ca|\1|"`
    echo ""
    echo "WARNING: GLOBUS_LOCATION not set, assuming:"
    echo "         GLOBUS_LOCATION=${GLOBUS_LOCATION}"
    echo ""
fi

if test -z "${GPT_LOCATION}"; then
    GPT_LOCATION=${GLOBUS_LOCATION}
    echo ""
    echo "WARNING: GPT_LOCATION not set, assuming:"
    echo "         GPT_LOCATION=${GPT_LOCATION}"
    echo ""
fi

if test ! -f ${GLOBUS_LOCATION}/libexec/globus-script-initializer; then
    echo ""
    echo "ERROR: Your globus install has not been setup correctly"
    echo "${GLOBUS_LOCATION}/libexec/globus-script-initializer not found"
    echo "You most likely need to run gpt-postinstall for this globus install"
    echo ""
    exit 1
fi

. ${GLOBUS_LOCATION}/libexec/globus-script-initializer

if test ! -f ${GLOBUS_LOCATION}/libexec/globus-sh-tools-vars.sh; then
    echo ""
    echo "ERROR: Invalid globus install and setup"
    echo "${libexecdir}/globus-sh-tools-vars.sh not found"
    echo ""
    exit 1
fi

globus_source ${libexecdir}/globus-sh-tools-vars.sh

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

short_usage="$PROGRAM_NAME [-help] [ options ...] [ openssl options ...]"

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

${short_usage}

  Note: Many of the following options can be used instead of allowing
        the script to interactively request configration info.  If
        its not clear what to do, let the interactive prompts guide you.

  Options:
    -help                 : shows this help message
    -?
    -h
    -usage
    -verbose              : Show verbose output
    -dir <loc>            : Will put the Simple CA in <loc>
    -force                : Overwite existing CA install if one exists
    -subject <CA subject> : Subject of the CA.  
                            If not specified the default is used.
                            Format: "cn=Globus, ou=Globus, o=Grid"
                            dashes in the subject must be escaped (\-) 
    -email <address>      : The email of the CA.  Default is empty.
    -days <num>           : Expiration of CA certificate 
                            (default: 1852 days or 5 years)
    -pass <password>      : CA password for private key.  Since the
                            password is visible to utilities, this
                            form should only be used where security is
                            not important.
    -nobuild              : Don't build the generated setup package
    -noint                : Force script to not be interactive.  This
                            will choose defaults for parameters specified
                            on the command line.  In this case the CA's
                            private key password will be: 'globus'.  This
                            option also implies -force.

    -openssl-help         : Show help text for openssl
 
    [<openssl options>] : Give openssl options to pass to the
                          openssl command.  Use with caution, some
                          options will conflict with this script.
EOF
}

if test ! -f ${libexecdir}/globus-args-parser-header; then
    echo ""
    echo "ERROR: Invalid globus install"
    echo "${libexecdir}/globus-args-parser-header not found"
    echo ""
    exit 1
fi

. $libexecdir/globus-args-parser-header

readCommandLine () {
  # Expects $* from the shell invocation

  while test ! "X$1" =  "X"
  do
    case $1 in
      -\?|-h|-help|-usage)
         long_usage
         exit 0
         ;;
     -dir)
         tmp_ca_dir="$2"
         if test -z "${tmp_ca_dir}"; then
            echo "ERROR: the -dir option expects a directory."
            exit 1;
         fi
         if test "`echo ${tmp_ca_dir} | cut -c1`" = "/"; then
            GRID_CA_DIR=${tmp_ca_dir}
         else
            GRID_CA_DIR=$PWD/$tmp_ca_dir
         fi
         
         shift ; shift
         ;;
     -force)
         force="yes"
         shift
         ;;
     -subject)
         shift
         while test "`echo ${1} | ${GLOBUS_SH_CUT-cut} -c1`" != "-"; do
             request_subject="${request_subject} ${1}"
             shift
         done
         ;;
     -email)
         request_email="${2}"
         shift ; shift
         ;;
     -days)
         request_days="${2}"
         shift ; shift
         ;;
     -pass)
         request_password="${2}"
         shift ; shift
         ;;
     -nobuild)
         nobuild="yes"
         shift
         ;;
     -noint)
         noint="yes"
         force="yes"
         shift
         ;;
     -verbose)
         verbose="yes"
         shift
         ;;
     -openssl-help)
         shift;
         openssl req -help;
         exit;
         ;;

     *)
         openssl_options="$openssl_options $1"
         shift;
         ;;
    esac
  done
}

readCommandLine $@;

# setup variables used by the script

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

CA_DIR_PERMS=0700
CA_ORG_NAME=""

CA_KEY_FILE=${GRID_CA_DIR}/private/cakey.pem
CA_CERT_FILE=${GRID_CA_DIR}/cacert.pem
CA_CERT_DAYS=1825 # 5 years

openssl_cmd=${GLOBUS_LOCATION}/bin/openssl

# functions that configure the CA
make_template_ca_setup
create_ca_directory
get_ca_info
save_ca_settings
generate_ca_certificate
generate_utils_package
emit_directions

if test -z "$nobuild"; then
    install_security_config
fi

if test -d "$tmp_ca_setup_dir" ; then
    ${GLOBUS_SH_RM-rm} -rf ${tmp_ca_setup_dir}
fi
#finish_simple_ca_setup


exit
