#!/bin/bash
set -eou pipefail


if ! which nix &>/dev/null; then
  echo "install nix with \`./dev/nix-up\`"
  exit 0
fi

# Configure the XMTP binary cache
XMTP_SUBSTITUTER="https://xmtp.cachix.org"
XMTP_PUBLIC_KEY="xmtp.cachix.org-1:nFPFrqLQ9kjYQKiWL7gKq6llcNEeaV4iI+Ka1F+Tmq0="

# Function to add value to a nix.conf setting if not already present
add_to_setting() {
  local conf_file="$1"
  local setting="$2"
  local value="$3"
  local use_sudo="$4"

  if grep -q "^${setting}" "$conf_file" 2>/dev/null; then
    # Setting exists, check if value is already there
    if ! grep "^${setting}" "$conf_file" | grep -q "$value"; then
      # Add value to existing setting
      # Use sed -i.bak for cross-platform compatibility (macOS BSD sed vs GNU sed)
      if [ "$use_sudo" = "true" ]; then
        sudo sed -i.bak "s|^\(${setting}.*\)|\1 ${value}|" "$conf_file" && sudo rm "${conf_file}.bak"
      else
        sed -i.bak "s|^\(${setting}.*\)|\1 ${value}|" "$conf_file" && rm "${conf_file}.bak"
      fi
      echo "Added $value to $setting"
    else
      echo "$value already in $setting"
    fi
  else
    # Setting doesn't exist, add it
    if [ "$use_sudo" = "true" ]; then
      echo "${setting} = ${value}" | sudo tee -a "$conf_file" > /dev/null
    else
      echo "${setting} = ${value}" >> "$conf_file"
    fi
    echo "Added $setting with $value"
  fi
}

# Configure XMTP cache
if ! grep -qF "xmtp.cachix.org" /etc/nix/nix.conf /etc/nix/nix.custom.conf ~/.config/nix/nix.conf 2>/dev/null; then
  echo ""
  echo "Configuring XMTP binary cache (avoids building dependencies from source)..."
  CURRENT_USER="$(whoami)"
  TRUSTED_USERS="$(nix config show trusted-users 2>/dev/null || true)"
  if echo "$TRUSTED_USERS" | grep -qwF "$CURRENT_USER"; then
    echo "User '$CURRENT_USER' is a trusted Nix user — configuring cache without sudo."
    NIX_CONF="${XDG_CONFIG_HOME:-$HOME/.config}/nix/nix.conf"
    mkdir -p "$(dirname "$NIX_CONF")"
    touch "$NIX_CONF"
    add_to_setting "$NIX_CONF" "extra-substituters" "$XMTP_SUBSTITUTER" "false"
    add_to_setting "$NIX_CONF" "extra-trusted-public-keys" "$XMTP_PUBLIC_KEY" "false"
  else
    echo "User '$CURRENT_USER' is not a trusted Nix user — sudo required to configure cache."
    NIX_CONF="/etc/nix/nix.conf"
    add_to_setting "$NIX_CONF" "extra-substituters" "$XMTP_SUBSTITUTER" "true"
    add_to_setting "$NIX_CONF" "extra-trusted-public-keys" "$XMTP_PUBLIC_KEY" "true"
  fi
  echo "XMTP binary cache configured."
else
  echo "XMTP binary cache already configured."
fi
