#!/bin/sh
# Install Ghobooz Indentification Radar into the local trust store. Does not change any other CA.
set -eu

cert=${1:-}
if [ -z "$cert" ] || [ ! -f "$cert" ]; then
  echo "Usage: sudo $0 /path/to/ghobooz-root.crt" >&2
  exit 1
fi

subject=$(openssl x509 -in "$cert" -noout -subject 2>/dev/null || true)
case "$subject" in
  *Ghobooz\ Indentification\ Radar*) ;;
  *)
    echo "This file is not the Ghobooz Indentification Radar ($subject)" >&2
    exit 1
    ;;
esac

if [ "$(id -u)" -ne 0 ]; then
  echo "Run as root so the system trust store can be updated." >&2
  exit 1
fi

dest_name="ghobooz-root.crt"
if [ -d /usr/local/share/ca-certificates ]; then
  cp "$cert" "/usr/local/share/ca-certificates/$dest_name"
  update-ca-certificates
elif [ -d /etc/pki/ca-trust/source/anchors ]; then
  cp "$cert" /etc/pki/ca-trust/source/anchors/ghobooz-root.crt
  update-ca-trust
else
  echo "No known system CA directory. Import $cert in the browser settings." >&2
  exit 1
fi

# Firefox / Chromium NSS profiles for the invoking user.
owner=${SUDO_USER:-}
if [ -n "$owner" ]; then
  home=$(getent passwd "$owner" | cut -d: -f6)
  if [ -n "$home" ] && [ -d "$home" ]; then
    find "$home" -name cert9.db -printf '%h\n' 2>/dev/null | while read -r dir; do
      certutil -A -n "Ghobooz Indentification Radar" -t "C,," -i "$cert" -d "sql:$dir" 2>/dev/null || true
    done
  fi
fi

echo "Ghobooz Indentification Radar is installed. Restart the browser, then open the site."
echo "Until this step, the browser correctly shows the site as untrusted."
