#!/bin/sh

#
# This file creates a p12 file based on your kerberos principal
# Idea from: Get-Cert.CMD Cygwin utils version 3.1 & changes to it by FERMILAB
# Author: Vijay murthi <murthi@fnal.gov>
#
#THIS SCRIPT IS DISTRIBUTED "AS IS". NO WARRANTY OF ANY KIND IS EXPRESSED OR IMPLIED. 
#YOU USE AT YOUR OWN RISK. THE AUTHOR WILL NOT BE LIABLE FOR DATA LOSS, DAMAGES, 
#LOSS OF PROFITS OR ANY OTHER KIND OF LOSS WHILE USING OR MISUSING THIS SCRIPT.
#



function execute()
{
    echo "Will exec : $@"
    $@
    if [ $? != 0 ]
    then
	echo "Error executing \"$@\""
	exit 1
    fi
}

#Check if command line args are present
echo "Asssuming you have already kerberos, ups/upd and kx509 installed on your machine.."

if [ -n "${1}" ]
then
        USER=$1
fi

#Check if you already have a TGT
klist -s
has_ticket=$?

#Prompt for creating a TGT
if [ $has_ticket = 1 ]
then
        execute "kinit ${USER}"
else
    echo "Ticket already found in cache"
fi

if [ ! -n ${SETUPS_DIR} ]
then
    echo "UPS/UPD not installed on your machine"
    exit 1
fi

. ${SETUPS_DIR}/setups.sh

execute "setup kx509"

execute "kx509"

export X509_USER_PROXY=/tmp/${USER}.pem

kxlist -p > /dev/null

cmd="openssl pkcs12 -export -passout pass: -in /tmp/${USER}.pem -out /tmp/${USER}.p12 -name ${USER}"
execute ${cmd}

echo ""
echo "****** Please Import file:/tmp/${USER}.p12 into your browser cache ********"
echo ""
echo "**Instructions http://computing.fnal.gov/security/WebBrowsers**"

