#!/bin/sh

# This script installs nix plus necessary settings for flakes

{ # Prevent execution if this script was only partially downloaded
    ensure_line_in_file() {
        FILE_DIRNAME=$(dirname "$2")
        test -e "$2" && grep -qxF "$1" "$2" || mkdir -p "${FILE_DIRNAME}" && echo "$1" >> "$2"
    }

    install_nix_config() {
        NIX_CONFIG_FILE_PATH="${HOME}/.config/nix/nix.conf"

        # Necessary to use the nix flakes feature:
        ensure_line_in_file "experimental-features = nix-command flakes" "${NIX_CONFIG_FILE_PATH}"

        # Necessary to prevent garbage collection of environments:
        ensure_line_in_file "keep-derivations = true" "${NIX_CONFIG_FILE_PATH}"
        ensure_line_in_file "keep-outputs = true" "${NIX_CONFIG_FILE_PATH}"

        echo "added nix config to ${NIX_CONFIG_FILE_PATH}"
    }

    oops() {
        echo "$0:" "$@" >&2
        exit 1
    }

    require_util() {
        command -v "$1" > /dev/null 2>&1 || \
            oops "you do not have '$1' installed, which I need to $2"
    }

    require_util curl "download nix installer"

    curl -sL https://nixos.org/nix/install | sh -s -- "$@" && \
        install_nix_config && \
        echo "nix installed successfully" && \
        echo "please restart shell now"
}
