#!/usr/bin/env bash
set -euo pipefail

# FRCS / VMS Sandbox cert bootstrapper for Linux
# Usage:
#   sudo ./frcs-install-certs.sh <pfx_file> <ica_cer_file> <rca_cer_file>
#
# Creates:
#   ~/frcs-devcert/developer-cert.pem
#   ~/frcs-devcert/developer-key.pem (chmod 600)
#   ~/frcs-devcert/developer-combined.pem
#
# Installs CA certs to system trust store (Debian/Ubuntu or RHEL/Fedora/CentOS).
# If libnss3-tools (certutil) is present, also imports CA certs to the user NSS DB (Chromium/Firefox).

if [[ $EUID -ne 0 ]]; then
  echo "Please run as root (sudo)."
  exit 1
fi

if [[ $# -ne 3 ]]; then
  echo "Usage: sudo $0 <DeveloperAuthenticationCertificate.pfx> <VMS_ICA1_Sandbox.cer> <VMS_RCA_Sandbox.cer>"
  exit 1
fi

PFX_FILE="$1"
ICA_FILE="$2"
RCA_FILE="$3"

for f in "$PFX_FILE" "$ICA_FILE" "$RCA_FILE"; do
  if [[ ! -f "$f" ]]; then
    echo "File not found: $f"
    exit 1
  fi
done

# Normalize extensions to .crt for system stores (they expect .crt PEM)
TMP_DIR="$(mktemp -d)"
cleanup() { rm -rf "$TMP_DIR"; }
trap cleanup EXIT

# Convert .cer (may be DER or PEM) to PEM .crt
to_pem_crt() {
  in="$1"; out="$2"
  # Detect if input is already PEM
  if grep -q "BEGIN CERTIFICATE" "$in" 2>/dev/null; then
    cp "$in" "$out"
  else
    # Assume DER; convert to PEM
    openssl x509 -inform der -in "$in" -out "$out"
  fi
}

ICA_CRT="$TMP_DIR/vms-ica1.crt"
RCA_CRT="$TMP_DIR/vms-rca.crt"
to_pem_crt "$ICA_FILE" "$ICA_CRT"
to_pem_crt "$RCA_FILE" "$RCA_CRT"

# Extract cert/key from PFX
USER_HOME="$(getent passwd "$SUDO_USER" | cut -d: -f6)"
OUT_DIR="$USER_HOME/frcs-devcert"
mkdir -p "$OUT_DIR"
chown "$SUDO_USER":"$SUDO_USER" "$OUT_DIR"

DEV_CERT="$OUT_DIR/developer-cert.pem"
DEV_KEY="$OUT_DIR/developer-key.pem"
DEV_COMBINED="$OUT_DIR/developer-combined.pem"

echo ">>> Extracting certificate and private key from PFX…"
# Prompt (without echo) for the PFX password
read -r -s -p "Enter PFX password: " PFXPASS
echo

# Extract leaf cert (no keys)
openssl pkcs12 -in "$PFX_FILE" -clcerts -nokeys -password pass:"$PFXPASS" -out "$DEV_CERT"
# Extract private key (unencrypted so tools can use it; you can encrypt it afterward if desired)
openssl pkcs12 -in "$PFX_FILE" -nocerts -nodes -password pass:"$PFXPASS" -out "$DEV_KEY"

chown "$SUDO_USER":"$SUDO_USER" "$DEV_CERT" "$DEV_KEY"
chmod 600 "$DEV_KEY"

cat "$DEV_CERT" "$DEV_KEY" > "$DEV_COMBINED"
chown "$SUDO_USER":"$SUDO_USER" "$DEV_COMBINED"
chmod 600 "$DEV_COMBINED"

echo ">>> Installing CA certificates to system trust store…"
# Detect distro family
OS_LIKE="$(. /etc/os-release; echo "${ID_LIKE:-$ID}")"

if echo "$OS_LIKE" | grep -qiE 'debian|ubuntu'; then
  DEST="/usr/local/share/ca-certificates"
  cp "$RCA_CRT" "$DEST/vms-rca.crt"
  cp "$ICA_CRT" "$DEST/vms-ica1.crt"
  update-ca-certificates
elif echo "$OS_LIKE" | grep -qiE 'rhel|fedora|centos|rocky|almalinux'; then
  DEST="/etc/pki/ca-trust/source/anchors"
  cp "$RCA_CRT" "$DEST/vms-rca.crt"
  cp "$ICA_CRT" "$DEST/vms-ica1.crt"
  update-ca-trust force-enable >/dev/null 2>&1 || true
  update-ca-trust extract
else
  echo "Unrecognized distro family ($OS_LIKE)."
  echo "Manually copy $RCA_CRT and $ICA_CRT into your distro's CA anchors directory and refresh the trust store."
fi

# Import to user NSS DB (Chrome/Chromium/Firefox) if possible
echo ">>> Checking for NSS (browser) certificate store…"
if command -v sudo -n true >/dev/null 2>&1; then :; fi # quiet sudo timestamp
if sudo -u "$SUDO_USER" command -v certutil >/dev/null 2>&1; then
  NSSDB="sql:$USER_HOME/.pki/nssdb"
  sudo -u "$SUDO_USER" mkdir -p "$USER_HOME/.pki/nssdb"
  # Initialize DB if not present
  if ! sudo -u "$SUDO_USER" certutil -d "$NSSDB" -L >/dev/null 2>&1; then
    sudo -u "$SUDO_USER" certutil -N -d "$NSSDB" --empty-password
  fi
  echo ">>> Importing CA certs into NSS DB ($NSSDB)…"
  sudo -u "$SUDO_USER" certutil -A -d "$NSSDB" -n "VMS RCA Sandbox" -t "CT,,C" -i "$RCA_CRT" || true
  sudo -u "$SUDO_USER" certutil -A -d "$NSSDB" -n "VMS ICA1 Sandbox" -t "CT,,C" -i "$ICA_CRT" || true
else
  echo "Skipping browser (NSS) import: 'certutil' not found. Install 'libnss3-tools' to enable."
fi

cat <<EOF

All done ✅

Created:
  $DEV_CERT
  $DEV_KEY   (chmod 600)
  $DEV_COMBINED

CA certificates installed to system trust store.
If you use curl or SDKs, you can test with:

  sudo -u "$SUDO_USER" curl --cert "$DEV_CERT" --key "$DEV_KEY" https://tap.sandbox.vms.frcs.org.fj/ -I

Tip: If a client requires a single PEM with both cert+key, use:
  $DEV_COMBINED

EOF

