# vim: ft=bash

# Override use_flake to inject a helper variable for prompts
# https://stackoverflow.com/a/1369211/14436105
eval "$(echo "orig_use_flake()"; declare -f use_flake | tail -n +2)"
function use_flake() {
    export DIRENV_USED="flake:${1:-$(basename "$PWD")}"
    orig_use_flake "$@";
}

# Convenience variable for generic prompt awareness
export DIRENV_USED="direnv"

# Helper to load nixpkgs into the environment (as if by `nix-shell -p`).
use_nixpkgs() {
    # NOTE: this just uses the flake to resolve the path for nixpkgs, but actually
    # does something more akin to `import <nixpkgs>` without flakes.
    # It may be equivalent in most cases, but just want to write it down somewhere.
    # https://docs.lix.systems/manual/lix/stable/command-ref/new-cli/nix.html#nix-file
    direnv_load nix shell --file flake:nixpkgs "$@" \
        --command direnv dump
}

use_flakes() {
    direnv_load nix shell \
        --argstr nixpkgsMeta "$(nix flake metadata --json flake:nixpkgs)" \
        --expr '{ nixpkgsMeta }:
            let
                nixpkgs = (builtins.fromJSON nixpkgsMeta).url;
                pkgs = import (builtins.getFlake nixpkgs) {};
            in {
                devShells.default = pkgs.mkShell {
                    packages = [ pkgs.hello ];
                };
            }
        ' \
        devShells.default \
        --command direnv dump
}

# TODO:
# some kind of fish exportable function helper would be nice, little bash cmds
# with `lib.mapAttrsToList pkgs.writeShellScriptBin` seems easier for the time being
