#!/bin/bash

# Imports CA certificates (.crt files) into a java keystore
# Copyright (C) 2009  Richard Adenling
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

if [ $# -eq 3 ]; then
	CERTDIR="$1"
	OUTFILE="$2"
	KEYTOOL="$3"
else
	echo "generate-java-cacerts <srcdir> <dstdir> <keytool>"
	exit 0;
fi

if [ ! -d "$CERTDIR" ]; then
	echo "$CERTDIR is not a directory"
	exit 1;
fi

if [ -f "$OUTFILE" ]; then
	echo "$OUTFILE exists"
	exit 1;
fi

if [ ! -x "$KEYTOOL" ]; then
	echo "$KEYTOOL does not exist or is not executable"
	exit 1;
fi

find $CERTDIR -type f -iname '*.crt' -print0 | while read -d $'\0' file
do
	echo "Adding $file"

	# Need to set LC_ALL becaue keytool uses localized "yes/no" input
	echo "yes" | LC_ALL="C" $KEYTOOL -import -noprompt -keystore $OUTFILE \
		-storepass 'changeit' -alias $(basename $file .crt) -file $file
done