#!/bin/sh
#  $Id$
#  Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
#  This software code contains proprietary information 
#  and should be treated as confidential.
#
#  Author: Patrick Caulfield
#
#  Generates a Certificate Request (CSR) for this host
#
# This is a generic product script used to establish an environment
# before starting/stopping a product or component.
# This script was built from shell library
#   $Id$
# This script has to run on every platform we support.  Any suggestions
# for improvement are welcome (but must be portable!)

# Version numbers
PRODUCT_VERSION="5.60.514"
PRODUCT_VERSION_FULL="5.60.514"
PRODUCT_VERSION_MAJOR=5
PRODUCT_VERSION_FEATURE=6
PRODUCT_VERSION_BUG=0
PRODUCT_VERSION_BUILD=514
PRODUCT_VERSION_BUILD_DECIMAL=514
PRODUCT_VERSION_AS_NUMBER=560514
PRODUCT_VERSION_CAB=5,6,0,514
PRODUCT_VERSION_RPM=5.60-514

# Product names
PRODUCT_FULL_NAME="Oracle Secure Global Desktop"
PRODUCT_SHORT_NAME="Secure Global Desktop"
PRODUCT_IDENT="SSGD"
PRODUCT_SHORT_FILENAME="Tarantella"
PRODUCT_LSBSCRIPTNAME="sun.com-sgd-base"
PRODUCT_LSBSCRIPT_RUN_LEVEL="90"
TSP_FULL_NAME="Oracle Secure Global Desktop Security Pack"
TSP_SHORT_NAME="Security Pack"
WCP_FULL_NAME="Oracle Secure Global Desktop Windows Connectivity Pack"
WCP_SHORT_NAME="Windows Connectivity Pack"
TN3270_FULL_NAME="Oracle Secure Global Desktop Mainframe Connectivity Pack"
TN3270_SHORT_NAME="Mainframe Connectivity Pack"
AS400_FULL_NAME="Oracle Secure Global Desktop AS/400 Connectivity Pack"
AS400_SHORT_NAME="AS/400 Connectivity Pack"
S1PSTK_FULL_NAME="Oracle Secure Global Desktop Channel for Sun ONE Portal Server"
S1PSIP_FULL_NAME="Oracle Secure Global Desktop Integration Pack for Sun ONE Portal Server"
S1PSTK_SHORT_NAME="Secure Global Desktop Channel for Sun ONE Portal Server"
S1PSIP_SHORT_NAME="Secure Global Desktop Integration Pack for Sun ONE Portal Server"

OBJECT_MGR_NAME="Object Manager"
ARRAY_MGR_NAME="Array Manager"
NATIVE_WIN16_FULL_NAME="Oracle Secure Global Desktop Native Client for Windows 3.1"
NATIVE_WIN16_SHORT_NAME="Native Client for Windows 3.1"
NATIVE_WIN32_FULL_NAME="Oracle Secure Global Desktop Native Client for Windows 95, 98 and NT"
NATIVE_WIN32_SHORT_NAME="Native Client for Windows 95, 98 and NT"
NATIVE_WYSE_FULL_NAME="Oracle Secure Global Desktop Native Client for Wyse"
NATIVE_WYSE_SHORT_NAME="Native Client for Wyse"
NATIVE_FULL_NAME="Oracle Secure Global Desktop Native Client"
NATIVE_SHORT_NAME="Native Client"
NATIVE_REGISTRY_NAME="Tarantella Native Client"
INTCLI_FULL_NAME="Oracle Secure Global Desktop Client"
INTCLI_SHORT_NAME="Client"
TCC_FULL_NAME="Oracle Secure Global Desktop Client"
TCC_HELPER_NAME="Oracle Secure Global Desktop Client Helper"
TCC_ACTIVEX_NAME="Oracle Secure Global Desktop ActiveX Control"
TCC_PLUGIN_NAME="Oracle Secure Global Desktop Netscape Plug-in"
T3COMPONENT_WIN_NAME="Oracle Secure Global Desktop Enhancement Module for Windows"
T3COMPONENT_UNIX_NAME="Oracle Secure Global Desktop Enhancement Module for UNIX(TM) and Linux Platforms"
T3COMPONENT_SHORT_UNIX_NAME="tem"
T3COMPONENT_NAME="Oracle Secure Global Desktop Enhancement Module"
T3COMPONENT_LSBSCRIPTNAME="sun.com-sgd-em"
T3COMPONENT_LSBSCRIPT_RUN_LEVEL="90"
GWCOMPONENT_UNIX_NAME="Oracle Secure Global Desktop Gateway for UNIX(TM) and Linux Platforms"
GWCOMPONENT_NAME="Oracle Secure Global Desktop Gateway"
GWCOMPONENT_SHORTNAME="SGD Gateway"
GWCOMPONENT_LSBSCRIPTNAME="sun.com-sgd-gw"
GWCOMPONENT_LSBSCRIPT_RUN_LEVEL="91"

# Watch the length of these names: IE refuses to remove packages if
# the name is too long.
ARCHIVE_NAME_ttalw="TCC Helper, version"
ARCHIVE_NAME_asad="3.x Framework Java Archive"
#ARCHIVE_NAME_tta="3.x Java Archive"
#ARCHIVE_NAME_tta="3.x Combined Java Archive"
ARCHIVE_NAME_tta="Client, "
ARCHIVE_NAME_tsp="3.x Security Java Archive"
ARCHIVE_NAME_proxy="3.x Proxy Java Archive"
WEBSTART_JAR_NAME="sgdwscs"
ARCHIVE_SUFFIX="K"

NS_REGKEY="java/download/com/tarantella/tta"

PRODUCT_VENDOR="Oracle Corporation, Inc."
PRODUCT_SHORT_VENDOR="Oracle"

# Capabilities:
# The format for the capabilities required by the client end of a
# connection is: CAPABILITIES_protocol_type_REQUIRED="expression"

# The format for the capabilities provided by the server end of a
# connection is: CAPABILITIES_protocol_type_PROVIDED="c1 c2 ... c3"

# Asad between a webtop client and server:
CAPABILITIES_ASAD_WEBTOPCLIENT_REQUIRED="(1.1 || 1.2)"
CAPABILITIES_ASAD_WEBTOPCLIENT_PROVIDED="1.1 1.2"

# Asad between two peer servers, or an admin tool and a server:
# 1.1 is core E3 array functionality.
# 1.2 is 3.01 array interoperability functionality.
# 2.1 is core Pisa client device mapping functionality (not a requirement)
CAPABILITIES_ASAD_PEER_REQUIRED="(1.1 || 1.2)"
CAPABILITIES_ASAD_PEER_PROVIDED="1.1 1.2 2.1"

# Client versions of server strings; same format, name prefixed by CLIENT
# Asad between a webtop client and server:
CLIENTCAPABILITIES_ASAD_WEBTOPCLIENT_REQUIRED="(1.1 || 1.2)"
CLIENTCAPABILITIES_ASAD_WEBTOPCLIENT_PROVIDED="1.1 1.2"

# Top-level item names in ENS datastore
DEFAULT_ROOT_ENS="organization"
SYSTEM_ROOT_ENS="Tarantella System Objects"
APP_ROOT_ENS="applications"
APPSERVER_ROOT_ENS="appservers"

WEB_SERVICES_VERSION=1.9


# be paranoid about the current path
if [ -d /bin ]; then
  PATH=/bin:$PATH
fi
if [ -d /sbin ]; then
  PATH=/sbin:$PATH
fi
if [ -d /usr/bin ]; then
  PATH=/usr/bin:$PATH
fi
if [ -d /usr/sbin ]; then
  PATH=/usr/sbin:$PATH
fi
if [ -d /etc ]; then
  PATH=/etc:$PATH
fi
export PATH

N=""
C=""
if echo -n | grep n > /dev/null
then
  C="\c"
else
  N="-n"
fi
case "$MACHINEARCH" in
i3li*|ppli*) N="$N -e" ;;
esac
_ss_headlines="--------------------------------------------------------------------------"

if [ -f $TTAMSG/common -a -f $TTAMSG/security_certrequest ]; then
  . $TTAMSG/common
  . $TTAMSG/security_certrequest
else
  echo "Unable to open message file: $TTAMSG/security_certrequest"
  exit 1
fi

GetPrivUsrGrp()
{
    cat $TTADATADIR/serverconfig/global/array.properties 2>/dev/null | awk -F= \
	'BEGIN { u="ttasys"; wu="ttaserv"; g="ttaserv" }
	$1 == "tarantella.config.array.privilegeduser" { u = $2 }
	$1 == "tarantella.config.array.webserveruser" { wu = $2 }
	$1 == "tarantella.config.array.privilegedgroup" { g = $2 }
	END { print u " " wu " " g }'
}
_privusrgrp=`GetPrivUsrGrp`
privusr=`expr "$_privusrgrp" : '\([^ ]*\) .*'`
webservusr=`expr "$_privusrgrp" : '.* \([^ ]*\) .*'`
privgrp=`expr "$_privusrgrp" : '.* \([^ ]*\)$'`

MkTtaDir()
{
    _newdirs="" _pflag=""
    case "$1" in
    -p) _pflag="-p"; shift
    esac
    for _d in "$@"; do
	while [ -n "$_d" ]; do
	    [ -d "$_d" ] && break
	    _newdirs="$_newdirs $_d"
	    _d=`dirname $_d`
	done
    done
    mkdir $_pflag "$@"
    [ -n "$_newdirs" ] && { chgrp $privgrp $_newdirs 2>/dev/null; chown $privusr $_newdirs 2>/dev/null; }
}

GetSafeName()
{
   MAX_LENGTH=64

   in_name="$1"
   var_name="$2"
   template_str="$3"

   safe_name="${in_name}"
   [ -x "/usr/bin/nawk" ] && AWK="nawk" || AWK="awk"

   # Calculate the length of the name passed in
   in_len=`echo "${in_name}" | ${AWK} '{print length($0)}'`

   # Calculate the max length of the name which can be
   # substituted in
   templateLen=`echo "${template_str}" | sed -e "s/${var_name}//g" | ${AWK} '{print length($0)}'`
   maxLen=`expr $MAX_LENGTH - ${templateLen}`
   # Check the limit
   if [ ${in_len} -gt ${maxLen} ]; then
      containsDots=`echo "${in_name}" | grep "\."`
      if [ -z "${containsDots}" ]; then
         # Cut to the max length
         safe_name=`echo "${in_name}" | cut -c -${maxLen}`
      else
         # Cut to the first .
         safe_name=`echo "${in_name}" | cut -d"." -f1`
      fi
   fi

   # Check the resulting string is short enough.
   # If not, repeat the process
   safe_len=`echo "${safe_name}" | ${AWK} '{print length($0)}'`
   if [ ${safe_len} -gt $MAX_LENGTH ]
   then
      safe_name=`GetSafeName "${safe_name}" "${var_name}" "${template_str}"`
   fi

   echo "${safe_name}"
}


OPENSSL_BINARY=openssl
TSPDIR=$TTADATADIR/tsp
KEY_PENDING_FILE=$TSPDIR/key.pending.pem
CERT_PENDING_FILE=$TSPDIR/cert.pending.pem
CSR_FILE=$TSPDIR/csr.pem
CONFIG_TMP=$TSPDIR/opensslcnf.$$
CONFIG_FILE="$CONFIG_TMP"
TEMP_KEY_FILE=$TSPDIR/tempk
TEMP_CSR_FILE=$TSPDIR/tempc

country=""
state=""
locality=""
orgname=""
ouname=""
email=""
hostname=""
keylen=""
altnames=""


usage()
{
  echo "$lf_certrequest_usage" 1>&2
}

short_usage() {
    echo "$1" 1>&2
    echo "$sf_certrequest_usage" 1>&2
}

#
# Does a "shift" only if there are some parameters left
#
SHIFT='if [ $# -ge 1 ]; then 
    last_shift=$1; 
    shift; 
else 
    short_usage "$l_missing_arg1$last_shift$l_missing_arg2";
    exit 1; 
fi'

# Check if the hostname is fully qualified
# to a first approximation is it fully qualified (has it got dots)?
# $1 : hostname
# $2 : 0 - just note the bad address
#    : 1 - see if user really wants to use it, or exit
validate_name()
{
    case "$1" in
    *.*)
	#on first inspection the name is ok
	;;
    *) 
	if [ $2 -eq 1 ]; then
	    # interactively check the hostname
	    echo ""
	    fq_ans=${s_no}
[ -z "${i18n_yes}" ] && i18n_yes="${a_yes}"
[ -z "${i18n_no}" ] && i18n_no="${a_no}"
[ -z "${i18n_case_yes}" ] && i18n_case_yes="${a_case_yes}"
[ -z "${i18n_case_no}" ] && i18n_case_no="${a_case_no}"
[ -z "${i18n_s_yes}" ] && i18n_s_yes="${s_yes}"
[ -z "${i18n_s_no}" ] && i18n_s_no="${s_no}"
[ "${l_host_not_fq1}$1${l_host_not_fq2}" != "NOPROMPT" ] && echo "${l_host_not_fq1}$1${l_host_not_fq2}"
echo # blank line between prompt and question
_valid=false
while [ $_valid = false ]
do
  echo $N "${l_host_ok_question} [$fq_ans] $C"
  read _answer
  if [ -z "$_answer" ]
  then
    _answer="$fq_ans"   # default
  fi
  case "$_answer" in
    [${i18n_case_yes}]* )
	    _answer=$i18n_s_yes
	    _valid=true
	    ;;
    [${i18n_case_no}]* )
	    _answer=$i18n_s_no
	    _valid=true
	    ;;
  esac
done
fq_ans="$_answer"


	    case "$fq_ans" in
	    ${s_yes})
		;;
	    *)  # incorrect name, exit
		echo "$l_host_bad_exit"
		exit 1
	    esac
	else
	    # simply indicate the problem
	    echo ""
	    echo "${l_host_not_fq1}$1${l_host_not_fq2}"
	fi
    esac

}

#
# parse command-line parameters
#
while [ -n "$1" ]; do
    case $1 in
        --country ) country=$2; eval "$SHIFT"; eval "$SHIFT";;
        --state ) state=$2; eval "$SHIFT"; eval "$SHIFT";;
        --locality ) locality=$2; eval "$SHIFT"; eval "$SHIFT";;
        --orgname ) orgname=$2; eval "$SHIFT"; eval "$SHIFT";;
        --ouname ) ouname=$2; eval "$SHIFT"; eval "$SHIFT";;
        --email ) email=$2; eval "$SHIFT"; eval "$SHIFT";;
        --keylength ) keylen=$2; eval "$SHIFT"; eval "$SHIFT";;
        --help ) usage; exit 0;;
	 * ) short_usage "$l_invalid_arg1$1$l_invalid_arg2"; exit 1;;
    esac
done

#
# Check we have all the required arguments
#
if [ -z "$country" -o -z "$state" -o -z "$orgname" ]; then
  short_usage "$l_not_enough_args"
  exit 1
fi

#
# Note we no longer check if the user specified a key length 
# that is sensible
#


#
# Make sure the country code is exactly 2 characters long
#
if [ `echo $country|wc -c` -ne 3 ]; then
  echo "$l_country_code"
  exit 2
fi

#
# See if TSP is installed.
#
if [ ! -x $TTABINDIR/bin/ttassl ]; then 
  echo 1>&2 "$lf_tspnotinstalled"
  exit 2
fi

#
# Create $TSPDIR if it doesn't exist
#
if [ ! -d $TSPDIR ]; then
  MkTtaDir $TSPDIR
  if [ $? != 0 ]; then
    echo "$l_cant_create_tspdir"
    exit 1
  fi
  chmod 751 $TSPDIR
fi


#
# Make the files only accessible by root.
#
umask 077

#
# Check for an existing key file and warn the user if one exists
#
if [ -f "$KEY_PENDING_FILE" ]; then
  regen_ans=${s_no}

[ -z "${i18n_yes}" ] && i18n_yes="${a_yes}"
[ -z "${i18n_no}" ] && i18n_no="${a_no}"
[ -z "${i18n_case_yes}" ] && i18n_case_yes="${a_case_yes}"
[ -z "${i18n_case_no}" ] && i18n_case_no="${a_case_no}"
[ -z "${i18n_s_yes}" ] && i18n_s_yes="${s_yes}"
[ -z "${i18n_s_no}" ] && i18n_s_no="${s_no}"
[ "${l_keyfile_already_exists}" != "NOPROMPT" ] && echo "${l_keyfile_already_exists}"
echo # blank line between prompt and question
_valid=false
while [ $_valid = false ]
do
  echo $N "${q_regen_key} [$regen_ans] $C"
  read _answer
  if [ -z "$_answer" ]
  then
    _answer="$regen_ans"   # default
  fi
  case "$_answer" in
    [${i18n_case_yes}]* )
	    _answer=$i18n_s_yes
	    _valid=true
	    ;;
    [${i18n_case_no}]* )
	    _answer=$i18n_s_no
	    _valid=true
	    ;;
  esac
done
regen_ans="$_answer"


  case "$regen_ans" in
    ${s_yes})
        ;;
    *)  echo "${l_not_generated}"
        exit 1
    esac
fi




#
# Get the host name
#
hostname=`$TTABINDIR/scripts/getconfig --extdns`
if [ -z "$hostname" ]; then
  echo "$l_hostname_error"
  exit 1
fi

#
# Check that the hostname is correct and it is what the user wants
#
    echo ""
    echo "${l_host_info1}${hostname}${l_host_info2}"

    echo "${l_host_ok_statement1}${hostname}${l_host_ok_statement2}"
    # check the name looks ok
    validate_name $hostname 0
    # does the admin think the name looks OK?
    hn_ans=${s_yes}

[ -z "${i18n_yes}" ] && i18n_yes="${a_yes}"
[ -z "${i18n_no}" ] && i18n_no="${a_no}"
[ -z "${i18n_case_yes}" ] && i18n_case_yes="${a_case_yes}"
[ -z "${i18n_case_no}" ] && i18n_case_no="${a_case_no}"
[ -z "${i18n_s_yes}" ] && i18n_s_yes="${s_yes}"
[ -z "${i18n_s_no}" ] && i18n_s_no="${s_no}"
[ "" != "NOPROMPT" ] && echo ""
echo # blank line between prompt and question
_valid=false
while [ $_valid = false ]
do
  echo $N "${l_host_ok_question} [$hn_ans] $C"
  read _answer
  if [ -z "$_answer" ]
  then
    _answer="$hn_ans"   # default
  fi
  case "$_answer" in
    [${i18n_case_yes}]* )
	    _answer=$i18n_s_yes
	    _valid=true
	    ;;
    [${i18n_case_no}]* )
	    _answer=$i18n_s_no
	    _valid=true
	    ;;
  esac
done
hn_ans="$_answer"

    case "$hn_ans" in
	${s_yes})
	    ;;
	*)  

	#get the new hostname (default is old one)
	newhostname=$hostname
	echo $N "$l_host_incorrect_name_q[$hostname] $C"
	read newhostname

	case "$newhostname" in
	    '') newhostname=$hostname
		;;
	    *)
		#if a user has typed a new name check it
		validate_name $newhostname 1
	    esac

	hostname=$newhostname

    esac

# Ask about additional hostnames
altnames=""
altname="dummy"
additionalhostnames_ans=${s_no}
[ -z "${i18n_yes}" ] && i18n_yes="${a_yes}"
[ -z "${i18n_no}" ] && i18n_no="${a_no}"
[ -z "${i18n_case_yes}" ] && i18n_case_yes="${a_case_yes}"
[ -z "${i18n_case_no}" ] && i18n_case_no="${a_case_no}"
[ -z "${i18n_s_yes}" ] && i18n_s_yes="${s_yes}"
[ -z "${i18n_s_no}" ] && i18n_s_no="${s_no}"
[ "" != "NOPROMPT" ] && echo ""
echo # blank line between prompt and question
_valid=false
while [ $_valid = false ]
do
  echo $N "${l_additionalhostnames_question} [$additionalhostnames_ans] $C"
  read _answer
  if [ -z "$_answer" ]
  then
    _answer="$additionalhostnames_ans"   # default
  fi
  case "$_answer" in
    [${i18n_case_yes}]* )
	    _answer=$i18n_s_yes
	    _valid=true
	    ;;
    [${i18n_case_no}]* )
	    _answer=$i18n_s_no
	    _valid=true
	    ;;
  esac
done
additionalhostnames_ans="$_answer"


if [ "$additionalhostnames_ans" = ${s_yes} ]; then
  echo ""
  echo "$l_host_altnames"
  echo "" 
  while [ -n "$altname"  ]; do
    echo $N "$l_host_subjectaltname$C"
    read altname
    if [ -z "$altname" ]; then
      if [ -n "$altnames" ]; then
        altnames="DNS:$hostname,$altnames"
      fi
      continue
    fi
    validate_name "$altname" 1
    if [ -z "$altnames" ]; then
      altnames="DNS:$altname"
    else 
      altnames="$altnames,DNS:$altname"
    fi
  done
fi


#
# Generate some randomness for the key
#
RANDFILE=$TSPDIR/ttarnd.$$
export RANDFILE
$TTABINDIR/bin/ttarandom >$RANDFILE
if [ $? != 0 ]; then
  echo "$l_random_error"
  exit 2
fi


#
# Generate a key pair
#
if [ -z "$keylen" ]; then
    keylen=2048
fi


$OPENSSL_BINARY genrsa -out $TEMP_KEY_FILE -rand $RANDFILE $keylen
if [ $? != 0 ]; then
  echo "$l_keygen_error"
  rm -f $RANDFILE
  exit 2
fi
rm -f $RANDFILE


# Create config file
cat <<EOF >$CONFIG_TMP
 # This definition stops the following lines choking if HOME isn't
 # defined.
 HOME                    = .
 RANDFILE                = /dev/urandom

 oid_section             = new_oids
 [ new_oids ]
 
 [ req ]
 default_bits            = 2048
 default_md              = sha256
 default_keyfile         = privkey.pem
 distinguished_name      = req_distinguished_name
EOF
 if [ -n "$altnames" ]; then
 echo "req_extensions = v3_req # Extensions to add to certificate request" >> $CONFIG_TMP
  fi

cat <<EOF >>$CONFIG_TMP
 string_mask = nombstr
  
 [ req_distinguished_name ]
 countryName                     = Country Name (2 letter code)
 countryName_default             = US
 countryName_min                 = 2
 countryName_max                 = 2

 stateOrProvinceName             = State or Province Name (full name)
 stateOrProvinceName_default     = Some-State

 localityName                    = Locality Name (eg, city)

 0.organizationName              = Organization Name (eg, company)
 0.organizationName_default      = Internet Widgits Pty Ltd

 organizationalUnitName          = Organizational Unit Name (eg, section)
 organizationalUnitName_default  =

 commonName                      = Full name of Tarantella host
 commonName_min                  = 4
 commonName_default              = .
 commonName_max                  = 64
 emailAddress                    = Email Address
 emailAddress_max                = 64

 [ v3_req ]
EOF

safehostname=`GetSafeName "${hostname}" "%HOST%" "%HOST%"`
if [ "${safehostname}" != "${hostname}" ]; then 
   if [ -z "${altnames}" ]; then
      altnames="DNS:${hostname}"
   else
      altnames="${altnames},DNS:${hostname}"
   fi
   hostname="${safehostname}"
fi

if [ -n "$altnames" ]; then
  echo " subjectAltName=$altnames" >> $CONFIG_TMP 
  CONFIG_FILE=$CONFIG_TMP
fi

#
# Generate a certificate request
#
$OPENSSL_BINARY req -out $TEMP_CSR_FILE -new -key $TEMP_KEY_FILE -config $CONFIG_FILE -rand "$RANDFILE" >/dev/null 2>/dev/null <<EOF
$country
$state
$locality
$orgname
$ouname
$hostname
$email
EOF

if [ $? != 0 ]; then
  echo "$l_csrgen_error"
  exit 2
fi

#
# Print out a summary of the CSR to stderr
#
echo ""
echo $_ss_headlines
echo "$h_csr_summary"
echo $_ss_headlines

$OPENSSL_BINARY req -in $TEMP_CSR_FILE -text -noout -config $CONFIG_FILE

# check that this is ok
csr_ans=${s_yes}

[ -z "${i18n_yes}" ] && i18n_yes="${a_yes}"
[ -z "${i18n_no}" ] && i18n_no="${a_no}"
[ -z "${i18n_case_yes}" ] && i18n_case_yes="${a_case_yes}"
[ -z "${i18n_case_no}" ] && i18n_case_no="${a_case_no}"
[ -z "${i18n_s_yes}" ] && i18n_s_yes="${s_yes}"
[ -z "${i18n_s_no}" ] && i18n_s_no="${s_no}"
[ "${l_csr_ok_statement}" != "NOPROMPT" ] && echo "${l_csr_ok_statement}"
echo # blank line between prompt and question
_valid=false
while [ $_valid = false ]
do
  echo $N "${l_csr_ok_question} [$csr_ans] $C"
  read _answer
  if [ -z "$_answer" ]
  then
    _answer="$csr_ans"   # default
  fi
  case "$_answer" in
    [${i18n_case_yes}]* )
	    _answer=$i18n_s_yes
	    _valid=true
	    ;;
    [${i18n_case_no}]* )
	    _answer=$i18n_s_no
	    _valid=true
	    ;;
  esac
done
csr_ans="$_answer"

    case "$csr_ans" in
	${s_yes})
	    ;;
	*)  
	# remove the temporary files and leave
	echo "$l_host_bad_exit"
	rm -f $TEMP_KEY_FILE
	rm -f $TEMP_CSR_FILE
	exit 1
    esac

#
# move all the temporary files into their new places and delete others
#

# If we are generating a key and the certfile is a symlink then just delete it
if [ -h $CERT_PENDING_FILE ];then
  rm -f $CERT_PENDING_FILE
fi

rm -f $KEY_PENDING_FILE
rm -f $CSR_FILE

cp $TEMP_KEY_FILE $KEY_PENDING_FILE
cp $TEMP_CSR_FILE $CSR_FILE

rm -f $TEMP_KEY_FILE
rm -f $TEMP_CSR_FILE
rm -f $CONFIG_TMP

# Set file owners
chown -R $privusr $TSPDIR
chgrp -R $privgrp $TSPDIR

#
# Print out the CSR
#
echo
echo "${l_csr_header}"
cat $CSR_FILE
echo "${l_csr_trailer}"
echo

exit 0
