#!/bin/sh
#  $Id: security_decryptkey.sh 109677 2015-03-31 12:24:31Z pc161604 $
#  Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
#  This software code contains proprietary information 
#  and should be treated as confidential.
#
#  Author: Sarah Bateman
#
#  Decrypts a private key 
#

# 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_decryptkey ]; then
  . $TTAMSG/common
  . $TTAMSG/security_decryptkey
else
  echo "Unable to open message file: $TTAMSG/security_decryptkey"
  exit 1
fi


OPENSSL_BINARY=openssl

encfile=""
decfile=""
outform="PEM"
inform="PEM"

usage() 
{
  echo "$lf_decryptkey_usage"
}

short_usage() {
    echo "$1" 1>&2
    echo "$sf_decryptkey_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 that the format is either PEM or DER
#
valid_format()
{
    case "$1" in
	PEM)
	    ;;
	DER)
	    ;;
	*)  
	short_usage "$l_decrypt_wrong_format"
	exit 1
    esac

}


#
# Parse command-line parameters
#
while [ -n "$1" ]; do
    case $1 in
        --enckey ) encfile=$2; eval "$SHIFT"; eval "$SHIFT";;
        --deckey ) decfile=$2; eval "$SHIFT"; eval "$SHIFT";;
        --format ) inform=$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 a encfilename and that it exists
#
if [ ! -n "$encfile" ]; then
    short_usage "$l_decrypt_no_encfilename"
    exit 1
else
    if [ ! -f "$encfile" ]; then
	echo "${l_decrypt_encfile_not_exist1}$encfile${l_decrypt_encfile_not_exist2}"
	exit 1
    fi  
fi

#
# check we have a decfilename and that it doesn't exist
#
if [ ! -n "$decfile" ]; then
    short_usage "$l_decrypt_no_decfilename"
    exit 1
else
    if [ -f "$decfile" ]; then
	echo "${l_decrypt_decfile_exists1}$decfile${l_decrypt_decfile_exists2}"
	exit 1
    fi  
fi


#
# check the format is correct
#
valid_format $inform

#
# Ensure protection on the files
#
umask 077




#
# DO THE CONVERSION
#
$OPENSSL_BINARY rsa -in $encfile -out $decfile -inform $inform -outform $outform
   
errcode=$?

echo ""
if [ $errcode -eq 0 ]; then 
    # success!
    echo "$l_decrypt_success"
else
    # failure :-(
    echo "$l_decrypt_failure"
fi
echo ""


exit 0
