#!/bin/bash

# (Ungetestet)

function _process() {
	# http://www.1st-setup.nl/wordpress/?p=105

	# TODO: Sicherheitslücke, weil jeder /tmp lesen kann und in $TMPFILE der Schlüssel UNVERSCHLÜSSELT gespeichert wird
	TMPFILE=$( mktemp )

	INFILE=$1

	# 1. Export you current certificate to a passwordless pem type
	openssl pkcs12 -in "$INFILE" -out "$TMPFILE" -nodes

	if [ $? -ne 0 ]; then
        	if [ -f "$TMPFILE" ]; then
	                rm "$TMPFILE"
        	fi
	        exit 1
	fi

	TMPFILE2=$( mktemp )

	# 2. Convert the passwordless pem to a new pfx file with password
	openssl pkcs12 -export -in "$TMPFILE" -out "$TMPFILE2"

	if [ $? -ne 0 ]; then
        	rm "$TMPFILE"
	        if [ -f "$TMPFILE2" ]; then
        	        rm "$TMPFILE2"
	        fi
        	exit 1
	fi

	# 3. Remove the temporary file
	rm "$TMPFILE"

	mv -f "$TMPFILE2" "$INFILE"

	exit $?
}

for f in $@
do
	echo "File: $f"
	_process "$f"
	if [ $? -eq 0 ]; then
		echo "OK"
	else
		echo "Error"
	fi
	echo ""
done
