#!/bin/sh

# Script to set up the default unit testing SSL keystore and truststore,
# also make a copy of other.keys with the same password of store.keys generated
# by make-ks.sh script for SSLCertificateUpdateTest
#
# The test begins with store.keys and merge.trust (contains certificates of keys
# in store.keys and other.keys), the client is using store.trust to access the
# store. Then replace store key store with new.keys, so it will be using key in
# new.keys (the key generated in other.keys). The reason change password of
# new.keys to be the same as the store.keys, is trying to avoid extra effort of
# updating the file password store, so the store can directly use the new key
# after replace key store.

keystore=other.keys
newkeystore=new.keys
truststore=other.trust
certfile=key.cert
pw=othertest
newpw=unittest
sharedalias=shared
pwfile=other.passwd

rm ${keystore}

# make self-signed key pair
keytool -genkeypair -keystore ${keystore} -storepass ${pw} -keypass ${pw} \
        -alias ${sharedalias} -dname 'cn="Unit Test"' -keyAlg RSA \
        -validity 36500 -storetype PKCS12

rm ${certfile}

# export cert
keytool -export -alias ${sharedalias} -file ${certfile} -keystore ${keystore} \
        -storepass ${pw}

rm ${truststore}

# import cert into truststore
keytool -import -alias ${sharedalias} -file ${certfile} \
        -keystore ${truststore} -storepass ${pw} \
        -storetype PKCS12 -noprompt

rm ${certfile}

# Create a password store file that tracks the store password
cat > ${pwfile} <<EOF
Password Store:
secret.keystore=${pw}
EOF

# Make copy of keystore with the same password of keystore generated by
# make-ks.sh
#
# Note that changing store password of a PKCS12 store will update the
# password of key as well. No need to run 'keytool -keypasswd', which
# would fail with an unsupported operation error.
cp ${keystore} ${newkeystore}

keytool -storepasswd -keystore ${newkeystore} -new ${newpw} \
        -storepass ${pw}
