#!/usr/bin/env bash

# SPDX-License-Identifier: MPL-2.0

# Usage: merge_nixos_config.sh <base_file> <extra_file> <merged_file>
#
# This script takes two NixOS configuration files, <base_file> and <extra_file>,
# as inputs and produces a new NixOS configuration file whose content is the
# combination of the two inputs. If the same key is set by both <base_file>
# and <extra_file>, then the value provided by <extra_file> takes precedence.
#
# A NixOS configuration file, usually named `configuration.nix`, is written in
# the following form:
#
# { config, lib, pkgs, ... }: {
#     key1 = value1;
#     key2 = value2;
# }

set -e

# Check for the correct number of arguments
if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <base_file> <extra_file> <merged_file>"
    exit 1
fi

BASE_FILE="$1"
EXTRA_FILE="$2"
MERGED_FILE="$3"

# Check if input files exist
if [ ! -f "$BASE_FILE" ]; then
    echo "Error: Base file not found at '$BASE_FILE'"
    exit 1
fi

if [ ! -f "$EXTRA_FILE" ]; then
    echo "Error: Extra file not found at '$EXTRA_FILE'"
    exit 1
fi

BASE_CONTENT=$(cat "$BASE_FILE")
EXTRA_CONTENT=$(cat "$EXTRA_FILE")

# Create the merged configuration file by embedding the file contents directly.
cat > "$MERGED_FILE" <<EOF
# This file is generated by merge_nixos_config.sh
# It merges two configuration files. Do not edit directly.

{ config, lib, pkgs, ... }:
let
  # The content of the original modules is embedded here.
  baseModule = (
$BASE_CONTENT
  );

  extraModule = (
$EXTRA_CONTENT
  );

  # Evaluate each module with the standard NixOS arguments
  base = baseModule { inherit config lib pkgs; };
  extra = extraModule { inherit config lib pkgs; };
in
  # Deeply merge the base and extra configurations.
  # The value from extra_file takes precedence.
  lib.recursiveUpdate base extra
EOF