# 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 versions.
# Usage: nix_update
function nix_update() {
	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 target="${1}"
	[[ "${target}" = "" ]] && target="default"

	if [[ "${target}" = "default" ]]; then
		NIX_SHELL="${target}" nix develop
	else
		NIX_SHELL="${target}" nix develop ".#${target}"
	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 ~/.config/linux/system/host/))

	_autocomplete_first ${targets[@]}
}

complete -F _comp_hosts nix_switch nix_rebuild