#!/bin/bash
# ============================================
# CA Certificate Deploy Script - FortiGate Deep Inspection
# Generated by Chuck's CA Distribution Server
# ============================================

set -e

CERT_DIR="/usr/local/share/ca-certificates"
CA_SERVER="https://certdeploy.schodel.com.au"
BACKUP_DIR="/tmp/ca-certs-backup-$(date +%Y%m%d%H%M%S)"

echo "👊 CA Certificate Deploy Script"
echo "================================"
echo ""

# Check root
if [ "$EUID" -ne 0 ]; then
  echo "❌ Run as root (sudo)"
  exit 1
fi

# Install curl if missing
if ! command -v curl &> /dev/null; then
  echo "📦 Installing curl..."
  apt-get update -qq && apt-get install -y -qq curl
fi

# Backup existing custom certs
echo "💾 Backing up existing custom certs..."
mkdir -p "$BACKUP_DIR"
cp -f "$CERT_DIR"/*.crt "$BACKUP_DIR/" 2>/dev/null || true

# Fetch cert list
echo "📋 Fetching certificate list..."
CERT_LIST=$(curl -sk "$CA_SERVER/api/certs")
CERT_COUNT=$(echo "$CERT_LIST" | python3 -c "import sys,json; print(json.load(sys.stdin)['count'])" 2>/dev/null || echo "0")

if [ "$CERT_COUNT" = "0" ]; then
  echo "❌ No certificates found on server"
  exit 1
fi

echo "📥 Downloading $CERT_COUNT certificate(s)..."

# Download each cert
CERT_NAMES=$(echo "$CERT_LIST" | python3 -c "import sys,json; [print(c['name']) for c in json.load(sys.stdin)['certs']]")

for cert_name in $CERT_NAMES; do
  echo "  ⬇️  $cert_name"
  # Convert .pem/.cer to .crt filename for update-ca-certificates
  dest_name="${cert_name%.pem}"
  dest_name="${dest_name%.cer}"
  dest_name="${dest_name%.crt}.crt"
  curl -sk "$CA_SERVER/certs/$cert_name" -o "$CERT_DIR/$dest_name"
  chmod 644 "$CERT_DIR/$dest_name"
done

# Update CA store
echo ""
echo "🔄 Updating CA certificate store..."
update-ca-certificates --fresh 2>&1 | tail -5

echo ""
echo "✅ System CA store updated."
echo ""

# ============================================
# Firefox — Install CA via enterprise policy
# ============================================
echo "🦊 Setting up Firefox CA trust..."

FF_DIRS=(
  "/usr/lib/firefox"
  "/usr/lib/firefox-esr"
  "/opt/firefox"
)

INSTALLED_FF=false

for ff_dir in "${FF_DIRS[@]}"; do
  if [ -d "$ff_dir" ]; then
    DIST_DIR="$ff_dir/distribution"
    mkdir -p "$DIST_DIR"
    
    CERT_ENTRIES=""
    for cert_file in "$CERT_DIR"/*.crt; do
      [ -f "$cert_file" ] || continue
      CERT_ENTRIES="${CERT_ENTRIES}        \"file://$cert_file\",
"
    done
    CERT_ENTRIES=$(echo -e "$CERT_ENTRIES" | sed '$ s/,$//')
    
    cat > "$DIST_DIR/policies.json" << POLICY_EOF
{
  "policies": {
    "Certificates": {
      "Install": [
$(echo -e "$CERT_ENTRIES")
      ]
    }
  }
}
POLICY_EOF
    
    chmod 644 "$DIST_DIR/policies.json"
    echo "  ✅ Firefox policy: $DIST_DIR/policies.json"
    INSTALLED_FF=true
  fi
done

# Snap Firefox — create per-user writable directory if needed
SNAP_FF_DIR="$HOME/snap/firefox/common"
mkdir -p "$SNAP_FF_DIR/distribution"
if [ -d "$SNAP_FF_DIR" ]; then
  SNAP_DIST="$SNAP_FF_DIR/distribution"
  mkdir -p "$SNAP_DIST"
  CERT_ENTRIES=""
  for cert_file in "$CERT_DIR"/*.crt; do
    [ -f "$cert_file" ] || continue
    CERT_ENTRIES="${CERT_ENTRIES}        \"file://$cert_file\",
"
  done
  CERT_ENTRIES=$(echo -e "$CERT_ENTRIES" | sed '$ s/,$//')
  cat > "$SNAP_DIST/policies.json" << POLICY_EOF
{
  "policies": {
    "Certificates": {
      "Install": [
$(echo -e "$CERT_ENTRIES")
      ]
    }
  }
}
POLICY_EOF
  chmod 644 "$SNAP_DIST/policies.json"
  echo "  ✅ Firefox snap policy: $SNAP_DIST/policies.json"
  INSTALLED_FF=true
fi

if [ "$INSTALLED_FF" = false ]; then
  echo "  ⚠️ Firefox not found. Create <firefox-dir>/distribution/policies.json manually."
fi

echo ""
echo "👊 All done! System + Firefox CA trust configured."
