#!/bin/bash
set -e

DATA_DIR="data"
mkdir -p "$DATA_DIR"

count_mozilla=0
count_google=0

############################################
# 1. Mozilla Root Store (PEM-only)
############################################

MOZ_URL="https://ccadb.my.salesforce-sites.com/mozilla/IncludedRootCertificateReportPEMCSV"

echo "Downloading Mozilla root store..."
curl -k -s "$MOZ_URL" -o "$DATA_DIR/mozilla.csv"

echo "Extracting PEM certificates from Mozilla CSV..."

cd "$DATA_DIR"

rm mozilla_*.pem || true

awk '
  # Start of PEM block
  /-----BEGIN CERTIFICATE-----/ {
    in_cert = 1
    file = sprintf("mozilla_%03d.pem", count++)
    print "-----BEGIN CERTIFICATE-----" > file
    next
  }

  # Inside PEM block
  in_cert {
    # If this line is the END marker, write it and close
    if ($0 ~ /-----END CERTIFICATE-----/) {
      print "-----END CERTIFICATE-----" >> file
      close(file)
      in_cert = 0
      next
    }

    # Otherwise write the line normally
    print >> file
  }
' mozilla.csv

cd ..

echo "Installing Mozilla certificates..."
for pem in "$DATA_DIR"/mozilla_*.pem; do
    der="${pem%.pem}.der"
    openssl x509 -inform PEM -outform DER -in "$pem" -out "$der"
    sudo security add-trusted-cert -k /Library/Keychains/System.keychain -d "$der"
    rm "$pem" "$der"
	count_mozilla=$((count_mozilla+1))
done


############################################
# 2. Google Chrome Root Store (PEM-only)
############################################

CHR_URL="https://raw.githubusercontent.com/chromium/chromium/refs/heads/main/net/data/ssl/chrome_root_store/root_store.certs"

echo "Downloading Google Chrome root store..."
curl -k -s "$CHR_URL" -o "data/chrome-certs.txt"


echo "Extracting PEM certificates from Google Chrome certs..."

rm chrome_*.pem || true

cd "$DATA_DIR"

awk '
  # Start of PEM block
  /-----BEGIN CERTIFICATE-----/ {
    in_cert = 1
    file = sprintf("chrome_%03d.pem", count++)
    print "-----BEGIN CERTIFICATE-----" > file
    next
  }

  # Inside PEM block
  in_cert {
    # If this line is the END marker, write it and close
    if ($0 ~ /-----END CERTIFICATE-----/) {
      print "-----END CERTIFICATE-----" >> file
      close(file)
      in_cert = 0
      next
    }

    # Otherwise write the line normally
    print >> file
  }
' chrome-certs.txt

cd ..


echo "Installing Google Chrome certificates..."
for pem in "$DATA_DIR"/chrome_*.pem; do
    der="${pem%.pem}.der"
    openssl x509 -inform PEM -outform DER -in "$pem" -out "$der"
    sudo security add-trusted-cert -k /Library/Keychains/System.keychain -d "$der"
    rm "$pem" "$der"
	count_google=$((count_google+1))
done

echo ""
echo "==================== Summary ===================="
echo "Mozilla certificates installed:      $count_mozilla"
echo "Google Chrome certificates installed: $count_google"
echo "================================================="
echo "Done."
