#!/usr/bin/env bash
# ECM Root CA — instalacija u sistemski trust store (Linux / macOS).
# Upotreba:  curl -fsSL https://login.ecm-iot.com/ca/install-ecm-ca.sh | sudo bash
set -euo pipefail

URL="https://login.ecm-iot.com/ca/ecm-root.crt"
EXPECT="BA:9A:C8:D0:57:4A:7F:7D:43:A3:C9:DB:41:6C:73:DF:64:88:76:4E:2B:F5:76:55:56:D0:1B:59:B4:F9:37:48"

TMP="$(mktemp)"; trap 'rm -f "$TMP"' EXIT
echo "» Preuzimam ECM Root CA…"
curl -fsSL "$URL" -o "$TMP"

echo "» Proveravam SHA-256 otisak…"
GOT="$(openssl x509 -in "$TMP" -noout -fingerprint -sha256 | sed 's/.*=//')"
if [ "$GOT" != "$EXPECT" ]; then
  echo "✗ OTISAK SE NE POKLAPA — prekidam (moguć podmetnut cert)."
  echo "  očekivano: $EXPECT"
  echo "  dobijeno:  $GOT"
  exit 1
fi
echo "  ✓ otisak OK"

if [ "$(uname -s)" = "Darwin" ]; then
  echo "» macOS: dodajem u System Keychain (traži admin lozinku)…"
  sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "$TMP"
else
  echo "» Linux: kopiram u /usr/local/share/ca-certificates i osvežavam…"
  sudo install -m 0644 "$TMP" /usr/local/share/ca-certificates/ecm-root.crt
  sudo update-ca-certificates
fi
echo "✓ ECM Root CA instaliran. Svi ECM servisi sada rade bez upozorenja."
