# Find Nix package path.
# Usage: nix_find <PACKAGE>
function nix_find() {
	local IFS=$'\n'
	local package="${1}"

	if [[ "${package}" = "" ]]; then
		help find_nix
		return 2
	fi

	local found=$(ls --classify /nix/store/ | grep "${package}".*/)

	if [[ "${found}" != "" ]]; then
		echo "/nix/store/${found%/}"
	else
		false
	fi
}

# Rebuild system.
# Optionally force the hostname.
# Usage: nix_rebuild [HOSTNAME]
function nix_rebuild() {
	local target="${1}"
	[[ "${target}" = "" ]] && target="${HOSTNAME}"

	cd ${HOME}/.config/linux/system
	nixos-rebuild boot --flake .#${target}
	cd -
}

# Rebuild and switch system.
# Optionally force the hostname.
# Usage: nix_switch [HOSTNAME]
function nix_switch() {
	local target="${1}"
	[[ "${target}" = "" ]] && target="${HOSTNAME}"

	cd ${HOME}/.config/linux/system
	nixos-rebuild switch --flake .#${target}
	cd -
}

# Update system.
# Optionally force the hostname.
# Usage: nix_update [HOSTNAME]
function nix_update() {
	local target="${1}"
	[[ "${target}" = "" ]] && target="${HOSTNAME}"

	cd ${HOME}/.config/linux/system
	nix flake update
	cd -
}

# Free up root space.
function nix_clean() {
	nix-collect-garbage -d
	_is_root && nix-store --gc
}

# Spawn shell with specified nix environment.
# Uses flake.nix in current dir by default.
# Usage: nix_shell [NAME]
function nix_shell() {
	local name="${1,,}"

	if [[ "${name}" = "" ]]; then
		NIX_SHELL=$(parse_alnum "${PWD##*/}") nix develop
	else
		NIX_SHELL="${name}" nix develop -f ~/.config/linux/shell/"${name^}".nix
	fi
}
alias shell="nix_shell"

# Spawn nix-shell with specified packages.
# Usage: nix_tmpshell <PACKAGES>
function nix_tmpshell() {
	local IFS=$'\n'
	local input=("${@}")
	local pkgs=()

	if [[ "${input}" = "" ]]; then
		help nix_tmpshell
		return 2
	fi

	for pkg in ${input[@]}; do
		pkgs+=("nixpkgs#${pkg}")
	done

	NIX_SHELL="${1}" nix shell ${pkgs[@]}
}
alias tmpshell="nix_tmpshell"

# Autocomplete with available hosts.
function _comp_hosts() {
	local IFS=$'\n'
	local targets=($(ls --classify ~/.config/linux/system/ | grep /$ | sed -e "s/\/$//"))

	_autocomplete_first ${targets[@]}
}

# Autocomplete with available shells.
function _comp_shells() {
	local IFS=$'\n'
	local targets=($(ls ~/.config/linux/shell/ | sed -e "s/.nix$//" | tr '[:upper:]' '[:lower:]'))

	_autocomplete_first ${targets[@]}
}

complete -F _comp_hosts nix_update nix_upgrade
complete -F _comp_shells nix_shell shell