#
# NixOS functions.
#

# Quote comments so we can avoid
try_source("quote-comments")

# Aliases
aliases['ls'] = 'eza -gb'
aliases['tree'] = 'eza --tree'

# Helper aliases.
aliases['push-store'] = 'nix path-info --all | cachix push polytheon'

# Use "rebuild" as a platform-agnostic rebuilding system.
aliases['rebuild'] = 'sudo nixos-rebuild --flake "/home/deprekated/dotfiles?submodules=1"'

# Allow non-free for regular commands.
$NIXPKGS_ALLOW_UNFREE=1


def _nix_locate(args, stdin=None, silent=False):
    """ Helper for finding a direct provider of a nix package. """

    raw_args = " ".join(args)
    nix-locate @(raw_args) | grep -v "^("


def _pkg_path(args, stdin=None, silent=False):

    raw_args = " ".join(args)
    result = $(nix eval --impure --expr  @('(import <nixpkgs> {}).' + raw_args + '.outPath'))

    if not silent:
        print(result.strip()[1:-1])

    return result.strip()[1:-1]


def _bin_path(args, stdin=None, silent=False):
    import pathlib

    # First, find the real path for our string.
    raw_args = " ".join(args)
    linkpath = $(which @(raw_args))

    if not linkpath:
        return None

    target = $(realpath @(linkpath))

	# If this is a Nix store path, trim it to just the package.
    if target.startswith("/nix/store"):
    	target = pathlib.Path(target)

    	while target.parent != p"/nix/store":
        	target = target.parent

    if not silent:
        print(target)

    return target


def _pkg_bins(args, stdin=None, silent=False):
    import pathlib

    raw_args = " ".join(args)
    target_path = None

	# If this is a file, get its path from that.
	# Otherwise, assume it's a nixpkgs name.
    if not pathlib.Path(raw_args).exists():
        target_path = _pkg_path(args, stdin, silent=True)
    else:
        target_path = _bin_path(args, stdin, silent=True)

    if not target_path:
        return

    bin_path = pf"{target_path}/bin"
    usr_path = pf"{target_path}/usr/bin"

    if bin_path.exists():
        ls @(bin_path)
    if usr_path.exists():
        ls @(usr_path)

aliases['nlocate'] = _nix_locate
aliases['pkgpath'] = _pkg_path
aliases['binpath'] = _bin_path
aliases['pkgbins'] = _pkg_bins
