#!/bin/sh

# To update key stores:
#
# 1. Send cert request via Apple dev site: download cert, and export
#    private key generated by request from "keys" section of Keychain
#    Access as e.g. "adhoc_apns_key.p12", password same as set in
#    "password=" line below. Put in "tls/source_certs".
#
# 2. Run "./make-apns-keystore appstore" to build apns-xxx.jks
#    keystore.
#
# 3. Profit!
#
# End up with keystore containing:
#
# * APNS developer key chained with downloaded intermediate cert
# (which seems to have the app bundle ID in it) and the WWDR CA cert.
#
# * Entrust 2048-bit root CA cert as trusted so that we can
# * authenticate the APNs server.

usage="$1"

if [ -z $usage ]; then
  echo "Usage: make-apns-keystore <deploy-type>"
  echo ""
  echo "e.g. make-apns-keystore adhoc"

  exit 1
fi

# PKCS12 password and store password (you should change this)
password="CHANGE-ME"

keystore_p12="apns-${usage}.p12"
keystore_jks="apns-${usage}.jks"

rm -f "$keystore_p12" "$keystore_jks"

echo "* Make PEM versions"

openssl pkcs12 -in "source_certs/${usage}_aps_key.p12" \
  -out "source_certs/${usage}_aps_key.pem" -nodes \
  -passin "pass:$password"

openssl x509 -inform der \
  -in "source_certs/${usage}_aps_cert.cer" \
  -out "source_certs/${usage}_aps_cert.pem"

openssl x509 -inform der \
  -in "source_certs/apple_WWDR_CA.cer" \
  -out "source_certs/apple_WWDR_CA.pem"

# NB: we create a PKCS12 keystore with developer+app private key and
# cert chain to WWDR CA and then import to JKS because keytool NPE's
# on the key import directly. We then need the Entrust CA cert to
# verify the APNs server (the latter from
# https://www.entrust.net/downloads/root_request.cfm#)

echo "* Create PKCS12 $keystore_p12"

openssl pkcs12 -export -out "$keystore_p12" \
  -inkey "source_certs/${usage}_aps_key.pem"  \
  -in "source_certs/${usage}_aps_cert.pem" \
  -certfile "source_certs/apple_WWDR_CA.pem" \
  -passout "pass:$password"

rm -f "source_certs/${usage}_aps_key.pem" \
      "source_certs/${usage}_aps_cert.pem" \
      "source_certs/apple_WWDR_CA.pem" 

echo "* Import $keystore_p12 to $keystore_jks"

keytool -v -importkeystore \
  -srckeystore "$keystore_p12" \
  -srcstoretype pkcs12 -srcstorepass "$password" \
  -destkeystore "$keystore_jks" \
  -deststoretype jks -deststorepass "$password" -noprompt

rm -f "$keystore_p12"

keytool -importcert -keystore "$keystore_jks" -alias "entrust_2048_ca" \
  -storepass "$password" \
  -file "source_certs/entrust_2048_ca.cer" -noprompt

echo "* Show contents"

keytool -list -storepass "$password" -keystore "$keystore_jks" \
  -storetype jks
