#!/bin/sh

set -e

# use the locale C.UTF-8
unset LC_ALL
LC_CTYPE=C.UTF-8
export LC_CTYPE

storepass='changeit'
if [ -f /etc/default/cacerts ]; then
    . /etc/default/cacerts
fi

arch=`dpkg --print-architecture`
JAR=/usr/share/ca-certificates-java/ca-certificates-java.jar

nsslib_name()
{
    if dpkg --assert-multi-arch 2>/dev/null; then
        echo "libnss3:${arch}"
    else
        echo "libnss3"
    fi
}

echo ""
if [ "$cacerts_updates" != yes ] || [ "$CACERT_UPDATES" = disabled ] || [ ! -e $JAR ]; then
    echo "updates of cacerts keystore disabled."
    exit 0
fi

if ! mountpoint -q /proc; then
    echo >&2 "the keytool command requires a mounted proc fs (/proc)."
    exit 1
fi

for jvm in java-7-openjdk-$arch java-7-openjdk \
           oracle-java7-jre-$arch oracle-java7-server-jre-$arch oracle-java7-jdk-$arch \
           java-8-openjdk-$arch java-8-openjdk \
           oracle-java8-jre-$arch oracle-java8-server-jre-$arch oracle-java8-jdk-$arch \
           java-9-openjdk-$arch java-9-openjdk \
           oracle-java9-jre-$arch oracle-java9-server-jre-$arch oracle-java9-jdk-$arch \
           java-10-openjdk-$arch java-10-openjdk \
           oracle-java10-jre-$arch oracle-java10-server-jre-$arch oracle-java10-jdk-$arch \
           java-11-openjdk-$arch java-11-openjdk \
           oracle-java11-jre-$arch oracle-java11-server-jre-$arch oracle-java11-jdk-$arch; do
    if [ -x /usr/lib/jvm/$jvm/bin/java ]; then
        export JAVA_HOME=/usr/lib/jvm/$jvm
        PATH=$JAVA_HOME/bin:$PATH
    	break
    fi
done

if dpkg-query --version >/dev/null; then
    nsspkg=$(dpkg-query -L "$(nsslib_name)" | sed -n 's,\(.*\)/libnss3\.so$,\1,p'|head -n 1)
    nsscfg=/etc/${jvm%-$arch}/security/nss.cfg
    nssjdk=$(test ! -f $nsscfg || sed -n '/nssLibraryDirectory/s/.*= *\(.*\)/\1/p' $nsscfg)
    if [ -n "$nsspkg" ] && [ -n "$nssjdk" ] && [ "$nsspkg" != "$nssjdk" ]; then
        ln -sf $nsspkg/libnss3.so $nssjdk/libnss3.so
    fi
    softokn3pkg=$(dpkg-query -L "$(nsslib_name)" | sed -n 's,\(.*\)/libsoftokn3\.so$,\1,p'|head -n 1)
    if [ -n "$softokn3pkg" ] && [ -n "$nssjdk" ] && [ "$softokn3pkg" != "$nssjdk" ]; then
        ln -sf $softokn3pkg/libsoftokn3.so $nssjdk/libsoftokn3.so
    fi
fi

do_cleanup()
{
    [ -z "$temp_jvm_cfg" ] || rm -f $temp_jvm_cfg
    if [ -n "$nsspkg" ] && [ -n "$nssjdk" ] && [ "$nsspkg" != "$nssjdk" ]
    then
        rm -f $nssjdk/libnss3.so
    fi
    if [ -n "$softokn3pkg" ] && [ -n "$nssjdk" ] \
       && [ "$softokn3pkg" != "$nssjdk" ]
    then
        rm -f $nssjdk/libsoftokn3.so
    fi
}

if java -Xmx64m -jar $JAR -storepass "$storepass"; then
    do_cleanup
else
    do_cleanup
    exit 1
fi

echo "done."
