#!/bin/bash

set -e

DAYS=3650
name="$1"
opsc_cert="$2"

[ -e "${name}KeyStore.pem" -a -e "${name}KeyStore" ] && exit 0

# The first existing directory is used for JAVA_HOME if needed.
JVM_SEARCH_DIRS="/usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-sun /usr/java/latest /usr/lib/jvm/jre-1.6.0"

# If JAVA_HOME has not been set, try to determine it.
if [ -z "$JAVA_HOME" ]; then
    # If keytool is in PATH, use a JAVA_HOME that corresponds to that. This is
    # both consistent with how the upstream startup script works, and how
    # Debian works (read: the use of alternatives to set a system JVM).
    if [ -n "`which keytool 2> /dev/null`" ]; then
        KEYTOOL=$(which keytool)
    elif [ -n "`which java 2> /dev/null`" ]; then
        # see if there's a keytool in the same bin dir as java
        java=`which java`
        # Dereference symlink(s)
        while true; do
            if [ -h "$java" ]; then
                java=`readlink "$java"`
                continue
            fi
            break
        done
        KEYTOOL="$(dirname $java)/keytool"
    fi

    if [ -z "$KEYTOOL" ]; then
        # No JAVA_HOME set and no keytool found in PATH, search for a JVM.
        for jdir in $JVM_SEARCH_DIRS; do
            if [ -x "$jdir/bin/keytool" ]; then
                JAVA_HOME="$jdir"
                KEYTOOL="$JAVA_HOME/bin/keytool"
                break
            fi
        done
    fi
else
    KEYTOOL="$JAVA_HOME/bin/keytool"
fi

# If we haven't set KEYTOOL by now, give up and and give the user a
# decent error message
if [ -z "$KEYTOOL" ]; then
    echo "Unable to find a java installation containing bin/keytool."
    echo 'Please set $JAVA_HOME to the location of your JRE installation.'
    exit 1
fi

$KEYTOOL -genkey -dname "cn=Unknown, ou=Unknown, o=Unknown, c=Unknown" \
    -alias agent_key -keypass opscenter -keystore "${name}KeyStore" \
    -storepass opscenter -validity "$DAYS"
$KEYTOOL -importkeystore -srckeystore "${name}KeyStore" -destkeystore "${name}KeyStore.p12" \
    -srcstoretype JKS -deststoretype PKCS12 -srcstorepass opscenter -deststorepass opscenter \
    -srcalias agent_key -destalias agent_key -srckeypass opscenter -destkeypass opscenter -noprompt

openssl pkcs12 -nokeys -in "${name}KeyStore.p12" -out "${name}KeyStore.pem" -passin pass:opscenter -passout pass:opscenter
$KEYTOOL -import -alias opscenter_cert -file "${opsc_cert}" \
    -keystore "${name}KeyStore" --storepass opscenter --noprompt

openssl x509 -outform der -in "${name}KeyStore.pem" -out "${name}KeyStore.der"