set unstable
flake_path := "path:/etc/nixos"

privesc := if which("sudo") != "" { 
    "sudo" 
} else if which("doas") != "" { 
    "doas" 
} else if which("run0") != "" { 
    "run0 --background="
} else if which("pkexec") != "" { 
    "pkexec" 
} else { 
    error("No privilege escalation tool found")
}

alias b := build
alias sw := switch
alias up := update
alias upp := update-input
alias gc := collect-garbage
alias ca := clean-all

default:
    @just --list

# Rebuild and switch
[group('nix')]
build:
    nh os build {{flake_path}}
    @rm -f result

# Don't want to enter password 3 times with doas/run0
[group('nix')]
switch:
    {{privesc}} nixos-rebuild switch --flake {{flake_path}}

[group('nix')]
boot:
    {{privesc}} nixos-rebuild boot --flake {{flake_path}}

# Update and switch
[group('nix')]
update:
    nh os switch --update {{flake_path}}

# Update specific input: `just upp nixpkgs`
[group('nix')]
update-input input:
    nix flake update {{input}}

# Test
[group('nix')]
test:
    nh os test {{flake_path}}

# Collect garbage
[group('nix')]
collect-garbage:
    nix-collect-garbage --delete-old
    {{privesc}} nix-collect-garbage -d
    {{privesc}} /run/current-system/bin/switch-to-configuration boot

# Run `nh clean all`
[group('nix')]
clean-all:
    nh clean all
