#!/bin/bash

function check_file() {
if [ ! -f $1 ]
then
    echo File: $1 does not exist!
    exit 1
fi
}

function check_status() {
if [ $? -ne 0 ]
then
    echo Failed to configure the QCG environment!
    echo The configuration is incorrect. Please contact QCG support unit.
    exit 1
fi
}

if [ -d ~/.globus ]
then
    echo "The ~/.globus directory with old configuration was detected."
    DATE=`date +%Y-%d-%d_%R`

    mv ~/.globus ~/.globus-$DATE
    rm ~/.globus -R -f
    echo "The previus version of the ~/.globus directory was moved to the: ~/.globus-$DATE"
fi

mkdir -p ~/.globus

case "$#" in
    1)
	check_file $1 
	
	echo "The key is being imported (userkey.pem) from the p12 certificate. Please provide the password used during generation of the certificate."
	openssl pkcs12 -nocerts -in $1 -out ~/.globus/userkey.pem
	check_status
		
	echo "The certificate is being imported (usercert.pem) from the p12 certificate. Please provide the password used during generation of the certificate."
	openssl pkcs12 -clcerts -nokeys -in $1 -out ~/.globus/usercert.pem
	check_status
	;;
    2)
	check_file $1
	check_file $2
	 
        cp -b $1 ~/.globus/usercert.pem
        cp -b $2 ~/.globus/userkey.pem
        ;;
    *)
        echo USAGE: 
	echo $0 certyfikat.p12
	echo $0 usercert.pem userkey.pem
	exit 1;
        ;;
esac
    														
chmod 600 ~/.globus/usercert.pem
chmod 600 ~/.globus/userkey.pem

cat > ~/.globus/cog.properties << EOF
usercert=$HOME/.globus/usercert.pem
userkey=$HOME/.globus/userkey.pem
EOF

if [ `grep -c "BEGIN ENCRYPTED PRIVATE KEY-----" ~/.globus/userkey.pem` -ne 0 ]; then
    echo UNSUPORTED USER KEY FORMAT DETECTED!
    echo The key will be converted to the RSA PRIVATE KEY one!
    
    cp ~/.globus/userkey.pem ~/.globus/userkey.pem_org
    echo Please provide the password to the key file.
    openssl pkcs8 -in ~/.globus/userkey.pem_org -out ~/.globus/userkey.pem
    check_status
    
    echo The key will be encrypted to be protected by password
    openssl rsa -in ~/.globus/userkey.pem -des3 -out ~/.globus/userkey.pem
    check_status
fi   

echo "The QCG environment was sucessfully configured. Please relogin."
