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

function check_status() {

if [ $1 -ne 0 ]
then
    echo
    echo Failed to configure the QCG environment!
    echo The most frequent reason of the failure is wrong password!!!
    echo 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)
        read -s -p "Enter password for the p12 file: " password
        export password
        echo
        
        check_file $1 
        openssl pkcs12 -password env:password -passout env:password -nocerts -nomacver -in $1 -out ~/.globus/userkey.pem
        check_status $?
        echo userkey.pem has been sucessfully imported!

        openssl pkcs12 -password env:password -clcerts -nokeys -nomacver -in $1 -out ~/.globus/usercert.pem
        check_status $?
        echo usercert.pem has been sucessfully imported!
        ;;
    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

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