# 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 --remove home-manager

	nix-channel --add https://nixos.org/channels/nixos-unstable nixos
	# nix-channel --add https://github.com/nix-community/home-manager/archive/master.tar.gz home-manager

	nix-channel --update
}

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

# 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. `Main` is default.
# Usage: nix_shell [NAME]
function nix_shell() {
	local name="${1,,}"
	[[ "${name}" = "" ]] && name="main"

	nix_shell="${name}" nix-shell ~/.config/linux/shell/"${name^}".nix
}
alias shell="nix_shell"

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

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

	nix_shell="${1}" nix-shell -p ${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