#!/bin/bash
set -euo pipefail

KEYSTORE="${1:-}"
if [[ -z "$KEYSTORE" ]]; then
  echo "Usage: $0 <keystore.p12>" >&2
  exit 1
fi

PASSWORD="password"

# Set up temp workspace
WORKDIR=$(mktemp -d)
trap "rm -rf $WORKDIR" EXIT

# Read input tar archive from stdin
tar -C "$WORKDIR" -xf -

ALIAS=$(cat "$WORKDIR/alias")
CERT="$WORKDIR/cert.pem"
KEY="$WORKDIR/key.pem"
CHAIN="$WORKDIR/chain.pem"

# Convert to PKCS#12 bundle
PKCS12="$WORKDIR/temp.p12"
openssl pkcs12 -export \
  -inkey "$KEY" \
  -in "$CERT" \
  -certfile "$CHAIN" \
  -name "$ALIAS" \
  -out "$PKCS12" \
  -passout pass:$PASSWORD

# If alias exists, delete it
if [[ -f "$KEYSTORE" ]]; then
  keytool -delete -alias "$ALIAS" -keystore "$KEYSTORE" \
    -storepass "$PASSWORD" -storetype PKCS12 || true
fi

# Import new entry
keytool -importkeystore \
  -destkeystore "$KEYSTORE" -deststoretype PKCS12 -deststorepass "$PASSWORD" \
  -srckeystore "$PKCS12" -srcstoretype PKCS12 -srcstorepass "$PASSWORD" \
  -alias "$ALIAS"
