#!/bin/env fish
function evalFlake --argument-names config property
    set -l argv $argv[3..]
    set -l flakePath "$(realpath (status dirname))/../.."
    argparse --ignore-unknown "apply=" "fallback=" json -- $argv

    if [ -z "$_flag_json" ]
        set -a argv --raw
    else
        set -a argv --json
    end

    if [ -z "$_flag_apply" ]
        set _flag_apply "_: _"
    end

    if [ -n "$VALHALLA_FLAKE_ROOT" ]
        set flakePath "$VALHALLA_FLAKE_ROOT"
    end

    if [ -n "$config" ]
        set config ".$config"
        set _flag_apply "_: ($_flag_apply) ((import $(realpath --relative-to (pwd) "$(status dirname)/../../lib/eval-attribute.nix")) _)"
    end

    PROPERTY="$property" \
        nix eval --impure --extra-experimental-features "nix-command flakes" \
        --apply "$_flag_apply" \
        "$flakePath#valhalla$config" \
        $argv

    or begin
        if [ -n "$_flag_fallback" ]
            echo "$_flag_fallback"
        else
            false
        end
    end
end