#!/usr/bin/env bash
set -euo pipefail

echo "[centos/dependencies] Installing CentOS build dependencies..."

dnf -y update
dnf -y install \
  git \
  gnupg2 \
  rsync \
  rpm-build \
  make \
  gcc \
  bash \
  curl-minimal \
  ca-certificates \
  python3 \
  python3-pip \
  sudo \
  xz

dnf clean all

# -----------------------------------------------------------------------------
# Persist CA bundle configuration system-wide (virgin-compatible)
# -----------------------------------------------------------------------------
detect_ca_bundle() {
  local candidates=(
    /etc/pki/tls/certs/ca-bundle.crt
    /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
    /etc/ssl/certs/ca-certificates.crt
    /etc/ssl/cert.pem
    /etc/ssl/ca-bundle.pem
  )

  for path in "${candidates[@]}"; do
    if [[ -f "$path" ]]; then
      echo "$path"
      return 0
    fi
  done

  return 1
}

CA_BUNDLE="$(detect_ca_bundle || true)"

if [[ -n "${CA_BUNDLE}" ]]; then
  echo "[centos/dependencies] Persisting CA bundle: ${CA_BUNDLE}"

  # 1) Make it available for login shells
  cat >/etc/profile.d/pkgmgr-ca.sh <<EOF
# Generated by package-manager
export NIX_SSL_CERT_FILE="${CA_BUNDLE}"
export SSL_CERT_FILE="${CA_BUNDLE}"
export REQUESTS_CA_BUNDLE="${CA_BUNDLE}"
export GIT_SSL_CAINFO="${CA_BUNDLE}"
EOF
  chmod 0644 /etc/profile.d/pkgmgr-ca.sh

  # 2) Ensure Nix uses it even without environment variables
  mkdir -p /etc/nix
  if [[ -f /etc/nix/nix.conf ]]; then
    # Replace existing ssl-cert-file or append it
    if grep -qE '^\s*ssl-cert-file\s*=' /etc/nix/nix.conf; then
      sed -i "s|^\s*ssl-cert-file\s*=.*|ssl-cert-file = ${CA_BUNDLE}|" /etc/nix/nix.conf
    else
      echo "ssl-cert-file = ${CA_BUNDLE}" >>/etc/nix/nix.conf
    fi
  else
    echo "ssl-cert-file = ${CA_BUNDLE}" >/etc/nix/nix.conf
  fi

else
  echo "[centos/dependencies] WARNING: No CA bundle found after installing ca-certificates."
fi

echo "[centos/dependencies] Done."
