#!/bin/bash
# Imports certs to a cert storage file.  Command line args:
#   $0 storage cert...
# Example:
#   certimp ./cacerts.bks certs/*
# If any "cert" is a directory, all files in that dir are added.  

# This script was tested to work with bouncycastle 1.43
# See http://www.bouncycastle.org
# Contains bash-isms.  This violates Debian policy for sysadmin scripts to be
# functional with any POSIX-compliant shell, specifically busybox.

if [ $# -lt 2 ] ; then
    echo "Usage: certimp cert_store.bks certs..."
    echo "The storage and the cert(s) are required."
fi

COUNTER=0
CERTSTORE=$1
shift
certs=($*)
if [ -e $CERTSTORE ] ; then
    rm $CERTSTORE || exit 4
fi
while /bin/true ; do
    n=${#certs[*]}
    if [ $n -le 0 ] ; then break ; fi
    : $((n--))
    cert=${certs[$n]}
    unset certs[$n]
    if [ ! -r $cert ] ; then
	echo "Can't read certificate $cert, skipped"
    elif [ -d $cert ] ; then
	certs+=(`eval echo $cert/*`)
    else
	keytool \
	    -importcert \
	    -v \
	    -noprompt \
	    -trustcacerts \
	    -alias "cert$COUNTER" \
	    -file <(openssl x509 -in $cert -outform DER) \
	    -keystore $CERTSTORE \
	    -storetype BKS \
	    -storepass SillyNoKeysHere \
	    -provider org.bouncycastle.jce.provider.BouncyCastleProvider \
	    -providerpath $PWD/bcprov.jar
	: $((COUNTER++))
    fi
done

