#!/bin/sh
#
# Change the pass phrase on a user's private key
#

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

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

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

PROGRAM_VERSION=`echo '$Revision: 1.5 $'| ${GLOBUS_SH_SED-sed} -e 's|\\$||g' -e 's|Revision: \(.*\)|\1|'`

VERSION="0.12"

PACKAGE="globus_gsi_cert_utils"

DIRT_TIMESTAMP="1055342205"
DIRT_BRANCH_ID="42"

short_usage="$PROGRAM_NAME [-help] [-version] [-file private_key_file]"

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

${short_usage}

   Changes the passphrase that protects the private key. Note that
   this command will work even if the original key is not password
   protected. If the -file argument is not given, the default location
   of the file containing the private key is assumed:

     -- The location pointed to by X509_USER_KEY
     -- If X509_USER_KEY not set, $HOME/.globus/userkey.pem

   Options
      -help, -usage    Displays usage
      -version         Displays version
      -file location   Change passphrase on key stored in the file at
                       the non-standard location 'location'.

EOF
}

globus_source $libexecdir/globus-args-parser-header $@

# SSL related need
PATH="${GLOBUS_LOCATION}/bin:${PATH}"
SSLEAY=${GLOBUS_LOCATION}/bin/ssleay
if [ -r ${GLOBUS_LOCATION}/bin/openssl ]; then
    SSLEAY="${GLOBUS_LOCATION}/bin/openssl"
fi


# DEFault Generated Files
DEF_GLOBUS_DIR="${HOME}/.globus"
DEF_KEY_FILE="${DEF_GLOBUS_DIR}/userkey.pem"

if [ -n "$X509_USER_KEY" ]; then
   private_key=${X509_USER_KEY}
else
   private_key=${DEF_KEY_FILE}
fi

if [ -n "$1" ]; then
    case "$1" in
	-file)
	    private_key="$2"
	    ;;
	--)
	    echo "" > /dev/null
	    ;;
	*)
	    globus_args_unrecognized_option "$1"
	    ;;
    esac
fi

${GLOBUS_SH_RM-rm} -f ${private_key}.new
${SSLEAY} rsa -des3 -in ${private_key} -out ${private_key}.new
if test $? -eq 0 ; then
    ${GLOBUS_SH_CHMOD-chmod} 0400 ${private_key}.new
    ${GLOBUS_SH_RM-rm} -f ${private_key}.old
    ${GLOBUS_SH_CP-cp} -p ${private_key} ${private_key}.old
    ${GLOBUS_SH_MV-mv} -f ${private_key}.new ${private_key}
else
    echo "Failed to change passphrase" >&2
    exit 1
fi

