0ea42e
#!/bin/sh
0ea42e
0ea42e
# Paths, names and functions definitions
0ea42e
NSSDB="/etc/pki/nssdb/"
0ea42e
COOLKEY_NAME="CoolKey PKCS #11 Module"
0ea42e
COOLKEY_LIBRARY="libcoolkeypk11.so"
0ea42e
OPENSC_NAME="OpenSC PKCS #11 Module"
0ea42e
OPENSC_LIBRARY="opensc-pkcs11.so"
0ea42e
0ea42e
add_module() {
0ea42e
	NAME="$1"
0ea42e
	LIBRARY="$2"
0ea42e
	modutil -add "$NAME" -dbdir "$NSSDB" -libfile "$LIBRARY"
0ea42e
}
0ea42e
remove_module() {
0ea42e
	NAME="$1"
0ea42e
	modutil -delete "$NAME" -dbdir "$NSSDB" -force
0ea42e
}
0ea42e
0ea42e
# Parse arguments. If wrong, print usage
0ea42e
TARGET="$1"
0ea42e
if [ "$TARGET" = "" ]; then
0ea42e
	# Print currently installed module
0ea42e
	PRINT_CURRENT="1"
0ea42e
elif [ "$TARGET" = "opensc" ] || [ "$TARGET" = "coolkey" ]; then
0ea42e
	: # Correct arguments
0ea42e
else
0ea42e
	echo "Simple tool to switch between OpenSC and Coolkey PKCS#11 modules in main NSS DB."
0ea42e
	echo "Usage: $0 [coolkey|opensc]"
0ea42e
	echo "    [coolkey|opensc]   says which of the modules should be used."
0ea42e
	echo "                       The other one will be removed from database."
0ea42e
	echo
0ea42e
	echo "    If there is no argument specified, prints the current module in NSS DB"
0ea42e
	exit 255
0ea42e
fi
0ea42e
0ea42e
if [ ! -x /usr/bin/modutil ]; then
0ea42e
	echo "The modutil is not installed. Please install package nss-util"
0ea42e
	exit 255
0ea42e
fi
0ea42e
0ea42e
# Find the current library in NSS DB
0ea42e
CURRENT="" # none
0ea42e
LIBS=$(modutil -rawlist -dbdir "$NSSDB" | grep "^library=")
0ea42e
if echo "$LIBS" | grep "$COOLKEY_NAME" > /dev/null; then
0ea42e
	CURRENT="coolkey"
0ea42e
fi
0ea42e
if echo "$LIBS" | grep "$OPENSC_NAME" > /dev/null; then
0ea42e
	if [ -n "$CURRENT" ]; then
0ea42e
		CURRENT="opensc coolkey"
0ea42e
		echo "There are both modules in NSS DB, which is not recommended."
0ea42e
		echo "I will remove the other."
0ea42e
	else
0ea42e
		CURRENT="opensc"
0ea42e
	fi
0ea42e
fi
0ea42e
0ea42e
if [ "$PRINT_CURRENT" = "1" ]; then
0ea42e
	echo "$CURRENT"
0ea42e
	exit 0
0ea42e
fi
0ea42e
0ea42e
# Do we need to change something?
0ea42e
if [ "$CURRENT" = "$TARGET" ]; then
0ea42e
	echo "The requested module is already in the NSS DB"
0ea42e
	exit 0
0ea42e
fi
0ea42e
0ea42e
# Do the actual change
0ea42e
if [ "$TARGET" = "opensc" ]; then
0ea42e
	add_module "$OPENSC_NAME" "$OPENSC_LIBRARY"
0ea42e
	remove_module "$COOLKEY_NAME"
0ea42e
fi
0ea42e
if [ "$TARGET" = "coolkey" ]; then
0ea42e
	add_module "$COOLKEY_NAME" "$COOLKEY_LIBRARY"
0ea42e
	remove_module "$OPENSC_NAME"
0ea42e
fi