# 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
}

# Switch to Unstable branch.
function nix_unstable() {
	nix-channel --remove nixos
	nix-channel --add https://nixos.org/channels/nixos-unstable nixos
	nix-channel --update
}

# Switch to Small Unstable branch (for server).
function nix_unstable_small() {
	nix-channel --remove nixos
	nix-channel --add https://nixos.org/channels/nixos-unstable-small nixos
	nix-channel --update
}

# Display current channel.
function nix_channel() {
	nix-channel --list
}

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

	nixos-rebuild switch -I nixos-config=/root/.config/linux/system/${target}/Configuration.nix
}

# Upgrade system. Applies after reboot.
# Optionally force the hostname.
# Usage: nix_upgrade [HOSTNAME]
function nix_upgrade() {
	local target="${1}"
	[[ "${target}" = "" ]] && target="${HOSTNAME}"

	nixos-rebuild boot --upgrade-all -I nixos-config=/root/.config/linux/system/${target}/Configuration.nix
}

# Free up root space.
function nix_clean() {
	nix-collect-garbage -d
	[[ "${UID}" = 0 ]] && nix-store --gc
}

# Spawn shell with nix environment, like LD support.
function nix_shell() {
	nix-shell ~/.config/linux/Shell.nix
}

# Spawn temporary shell.
function shell() {
	nix-shell -p "${@}"
}

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

	_autocomplete_first ${targets[@]}
}

complete -F _comp_hosts nix_update nix_upgrade