#!/usr/bin/env bash
# ============================================================================
# install-linux.sh — Install GWS device certificate on Linux
#
# Usage:
#   ./install-linux.sh /path/to/cert.p12
#   ./install-linux.sh /path/to/cert.p12 /path/to/ca.crt
#
# What it does:
#   1. Imports .p12 client cert to NSS database (used by Chrome/Chromium)
#   2. Imports CA cert to system trust store
#
# Requires: libnss3-tools (certutil), openssl
# ============================================================================
set -euo pipefail

P12_PATH="${1:?Usage: $0 /path/to/cert.p12 [/path/to/ca.crt]}"
CA_PATH="${2:-}"

echo ""
echo "========================================"
echo "  GWS Cert Installer - Linux"
echo "========================================"
echo ""

if [[ ! -f "$P12_PATH" ]]; then
  echo "[ERROR] File not found: $P12_PATH"
  exit 1
fi

# Check dependencies
for cmd in certutil openssl; do
  if ! command -v "$cmd" &>/dev/null; then
    echo "[ERROR] Required: $cmd"
    echo "  Install: sudo apt install libnss3-tools openssl"
    exit 1
  fi
done

# NSS database path (Chrome/Chromium)
NSS_DB="$HOME/.pki/nssdb"
if [[ ! -d "$NSS_DB" ]]; then
  echo "Creating NSS database at $NSS_DB..."
  mkdir -p "$NSS_DB"
  certutil -d sql:"$NSS_DB" -N --empty-password
fi

# --- Step 1: Import client cert ---
echo "[1/2] Importing client certificate to NSS database..."
echo "Enter the .p12 import password (leave empty if none):"
read -s P12_PASS
echo ""

pk12util -i "$P12_PATH" -d sql:"$NSS_DB" -W "$P12_PASS" \
  && echo "  OK: Client cert imported" \
  || { echo "[ERROR] Import failed. Check password."; exit 1; }

# --- Step 2: Import CA cert ---
if [[ -n "$CA_PATH" && -f "$CA_PATH" ]]; then
  echo "[2/2] Importing CA certificate..."

  # NSS trust
  certutil -d sql:"$NSS_DB" -A -t "C,," -n "GWS-Device-CA" -i "$CA_PATH" \
    && echo "  OK: CA cert added to NSS database"

  # System trust (Debian/Ubuntu)
  if [[ -d /usr/local/share/ca-certificates ]]; then
    sudo cp "$CA_PATH" /usr/local/share/ca-certificates/gws-device-ca.crt
    sudo update-ca-certificates
    echo "  OK: CA cert added to system trust store"
  fi
else
  echo "[2/2] No CA cert provided, skipping."
fi

echo ""
echo "Done! Restart Chrome/Chromium to use the certificate."
echo ""
echo "To verify: chrome://settings/certificates → Your Certificates"
echo ""
