export _nix_system_config="${HOME}/.config/linux/system"

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

	nixos-rebuild boot --flake "${_nix_system_config}#${target}"
}

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

	nixos-rebuild switch --flake "${_nix_system_config}#${target}"
}

# Update system versions.
# Usage: nix_update
function nix_update() {
	nix flake update "${_nix_system_config}"
}

# Free up root space.
function nix_prune() {
	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"

# Build live image.
function nix_live() {
	nix build "${_nix_system_config}#nixosConfigurations.live.config.system.build.isoImage"
}

# 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