# NixOS

This document contains general notes about NixOS that are independent of my NixOS configuration.

## Table of Contents

<!-- TOC -->
* [NixOS](#nixos)
  * [Table of Contents](#table-of-contents)
  * [Misc](#misc)
  * [NixOS upgrades](#nixos-upgrades)
  * [niv: Dependency management](#niv-dependency-management)
    * [Add Home Manager with niv](#add-home-manager-with-niv)
    * [Add NUR with niv](#add-nur-with-niv)
  * [System information](#system-information)
  * [Search for packages](#search-for-packages)
  * [Search for options](#search-for-options)
  * [Search which package owns a file](#search-which-package-owns-a-file)
  * [List files of package](#list-files-of-package)
  * [Package runtime dependency report](#package-runtime-dependency-report)
  * [Nix profiles](#nix-profiles)
    * [Switch to previous system profile](#switch-to-previous-system-profile)
    * [List system profiles](#list-system-profiles)
    * [Garbage collection - Keep most recent X system profiles](#garbage-collection---keep-most-recent-x-system-profiles)
    * [Garbage collection - Delete system profiles older than X days](#garbage-collection---delete-system-profiles-older-than-x-days)
    * [why-depends: Why is a package/dependency installed](#why-depends-why-is-a-packagedependency-installed)
    * [Compare two system profiles](#compare-two-system-profiles)
  * [NixOS configuration debugging](#nixos-configuration-debugging)
  * [Show Nix configuration](#show-nix-configuration)
  * [Evaluate NixOS configuration to JSON](#evaluate-nixos-configuration-to-json)
  * [Evaluate expressions in the context of a NixOS configuration managed with Colmena](#evaluate-expressions-in-the-context-of-a-nixos-configuration-managed-with-colmena)
  * [Evaluate expressions](#evaluate-expressions)
  * [Escape strings](#escape-strings)
  * [Run AppImages](#run-appimages)
  * [Audio troubleshooting - Realtek ALC898 Audio Codec on ASRock Z77 Extreme 4](#audio-troubleshooting---realtek-alc898-audio-codec-on-asrock-z77-extreme-4)
  * [Graphic drivers](#graphic-drivers)
  * [XDG mimes, desktop files](#xdg-mimes-desktop-files)
  * [Additional resources](#additional-resources)
    * [Nix Pills](#nix-pills)
    * [Papers](#papers)
<!-- TOC -->

## Misc

* There is controversy about flakes, rather use channels (e.g. with niv)
* Prins, P., Suresh, J. and Dolstra, E., "Nix fixes dependency hell on all Linux distributions," [Archived](https://web.archive.org/web/20081226010942/http://www.linux.com/feature/155922) December 26, 2008, at the Wayback Machine linux.com, December 22, 2008

## NixOS upgrades

See [NixOS Upgrades](NixOS%20Upgrades.md).

## niv: Dependency management

* https://nix.dev/tutorials/first-steps/towards-reproducibility-pinning-nixpkgs#dependency-management-with-niv

niv:

> Easy dependency management for Nix projects.
>
> Nix is a very powerful tool for building code and setting up environments. niv complements it by making it easy to
> describe and update remote dependencies (URLs, GitHub repos, etc). It is a simple, practical alternative to Nix
> flakes.
>
> https://github.com/nmattia/niv

> Niv is an easy dependency management for Nix projects with package pinning.
>
> https://github.com/mikeroyal/NixOS-Guide

Initialize:

```shell
niv init
```

Change the tracking branch of nixpkgs from unstable to 23.05:

```shell
niv modify nixpkgs --branch nixos-23.05
```

Add nixpkgs unstable:

```shell
niv add NixOS/nixpkgs -n unstable -b nixpkgs-unstable
```

### Add Home Manager with niv

Home Manager:

> [Home Manager] allows declarative configuration of user specific (non-global) packages and dotfiles.
>
> To avoid breaking users' configurations, Home Manager is released in branches corresponding to NixOS releases (
> e.g. `release-23.05`).
>
> Home Manager provides both the channel-based setup and the flake-based one.
>
> https://github.com/nix-community/home-manager

Check your channel:

```shell
sudo nix-channel --list
#=> nixos https://nixos.org/channels/nixos-23.05
```

Use the corresponding branch:

```shell
niv add nix-community/home-manager -n home-manager -b release-23.05
```

### Add NUR with niv

> The Nix User Repository (NUR) is community-driven meta repository for Nix packages.
>
> ... packages are built from source and are not reviewed by any Nixpkgs member.
>
> https://github.com/nix-community/NUR

```shell
niv add nix-community/NUR -n NUR
```

## System information

```shell
nix-info -m
```
```
 - system: `"x86_64-linux"`
 - host os: `Linux 6.1.51, NixOS, 23.05 (Stoat), 23.05.3242.da5adce0ffaf`
 - multi-user?: `yes`
 - sandbox: `yes`
 - version: `nix-env (Nix) 2.13.5`
 - channels(root): `"nixos-23.05"`
 - nixpkgs: `/nix/var/nix/profiles/per-user/root/channels/nixos`
```

## Search for packages

* https://search.nixos.org/packages

## Search for options

* https://search.nixos.org/options
    * Or `man configuration.nix`
* https://mipmip.github.io/home-manager-option-search
    * Or `man home-configuration.nix`

## Search which package owns a file

```shell
# Note how your shell prefix changes.
nix-shell -p nix-index
```
```shell
# Either build the index manually (requires >12GB RAM):
nix-index
# Or download weekly build:
mkdir -p ~/.cache/nix-index/ && wget -q -N https://github.com/nix-community/nix-index-database/releases/latest/download/index-x86_64-linux -O ~/.cache/nix-index/files

# Then search for a file
nix-locate --whole-name '/bash'
```

## List files of package

* https://discourse.nixos.org/t/list-files-of-package/25830/2

Example for `nano`:

```shell
find $(nix-build '<nixpkgs>' -A nano --no-link)
```

Excerpt of the result:

```
/nix/store/jqvxmx65mfinbsm6db9kmcqmphl44xhp-nano-7.2/share/nano
/nix/store/jqvxmx65mfinbsm6db9kmcqmphl44xhp-nano-7.2/share/nano/asm.nanorc
/nix/store/jqvxmx65mfinbsm6db9kmcqmphl44xhp-nano-7.2/share/nano/autoconf.nanorc
```

## Package runtime dependency report

- https://github.com/nix-how/nix-demos#runtimereport -> https://www.nmattia.com/posts/2019-10-08-runtime-dependencies/

Example: Licenses and maintainers of runtime dependencies of package `hello`:

```shell
nix --extra-experimental-features flakes --extra-experimental-features nix-command bundle --bundler github:nix-how/nix-demos#runtimeReport nixpkgs#hello
cat hello-*-report
```
```console
  ---------------------------------
  |        OFFICIAL REPORT        |
  |   requested by: the lawyers   |
  |    written by: yours truly    |
  |    TOP SECRET - TOP SECRET    |
  ---------------------------------

runtime dependencies of hello-2.12.1:
 - libunistring-1.1 (lgpl3Plus) maintained by 
 - xgcc-13.2.0 (gpl3Plus) maintained by Patrick Hilhorst, Vladimír Čunát, John Ericson
 - hello-2.12.1 (gpl3Plus) maintained by Eelco Dolstra
 - libidn2-2.3.4 (lgpl3Plus, gpl2Plus, gpl3Plus) maintained by Franz Pletz
 - glibc-2.38-27 (lgpl2Plus) maintained by Eelco Dolstra, Maximilian Bosch, Connor Baker
```

Example: `nano`

```console
  ---------------------------------
  |        OFFICIAL REPORT        |
  |   requested by: the lawyers   |
  |    written by: yours truly    |
  |    TOP SECRET - TOP SECRET    |
  ---------------------------------

runtime dependencies of nano-7.2:
 - libunistring-1.1 (lgpl3Plus) maintained by 
 - file-5.45 (bsd2) maintained by Doron Behar
 - xgcc-13.2.0 (gpl3Plus) maintained by Patrick Hilhorst, Vladimír Čunát, John Ericson
 - nano-7.2 (gpl3Plus) maintained by Joachim Fasting, Tim Steinbach
 - libidn2-2.3.4 (lgpl3Plus, gpl2Plus, gpl3Plus) maintained by Franz Pletz
 - zlib-1.3 (zlib) maintained by nobody
 - glibc-2.38-27 (lgpl2Plus) maintained by Eelco Dolstra, Maximilian Bosch, Connor Baker
 - ncurses-6.4 (mit) maintained by nobody
```

Example: `firefox`

```console
  ---------------------------------
  |        OFFICIAL REPORT        |
  |   requested by: the lawyers   |
  |    written by: yours truly    |
  |    TOP SECRET - TOP SECRET    |
  ---------------------------------

runtime dependencies of firefox-121.0.1:
 - libunistring-1.1 (lgpl3Plus) maintained by 
 - perl5.38.2-WWW-RobotRules-6.02 (artistic1, gpl1Plus) maintained by nobody
 - gdbm-1.23 (gpl3Plus) maintained by Rahul Gopinath
 - perl5.38.2-HTTP-CookieJar-0.014 (asl20) maintained by nobody
 - gmp-with-cxx-6.3.0 (lgpl3Only, gpl2Only) maintained by Rahul Gopinath
 - libXdamage-1.1.6 (no license) maintained by nobody
 - expat-2.5.0 (mit) maintained by nobody
 - gnutls-3.8.2 (lgpl21Plus) maintained by Vladimír Čunát
 - dbus-1.14.10 (gpl2Plus) maintained by Jan Tojnar
 - systemd-minimal-libs-254.6 (lgpl21Plus) maintained by Florian Klink, Finn Behrens
 - gnutar-1.35 (gpl3Plus) maintained by 
 - util-linux-minimal-2.39.3 (gpl2Only, gpl2Plus, gpl3Plus, lgpl21Plus, bsd3, bsdOriginalUC, publicDomain) maintained by nobody
 - gdk-pixbuf-2.42.10 (lgpl21Plus) maintained by Eelco Dolstra, Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey
 - tracker-3.6.0 (gpl2Plus) maintained by Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey
 - libXext-1.3.5 (no license) maintained by nobody
 - openssl-3.0.12 (asl20) maintained by Markus Theil
 - at-spi2-core-2.50.0 (lgpl21Plus) maintained by Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey, Michael Raskin
 - libXtst-1.2.4 (no license) maintained by nobody
 - gcc-13.2.0 (gpl3Plus) maintained by Patrick Hilhorst, Vladimír Čunát, John Ericson
 - bzip2-1.0.8 (bsdOriginal) maintained by Jörg Thalheim
 - perl5.38.2-TimeDate-2.33 (artistic1, gpl1Plus) maintained by nobody
 - libsoup-3.4.4 (lgpl2Plus) maintained by Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey, Jason O'Conal, Michael Raskin
 - dconf-0.40.0 (lgpl21Plus) maintained by Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey
 - cairo-1.18.0 (lgpl2Plus, mpl10) maintained by nobody
 - libxcrypt-4.4.36 (lgpl21Plus) maintained by Misha Gusarov, Martin Weinelt
 - libxml2-2.12.3-unstable-2023-12-14 (mit) maintained by Eelco Dolstra, Jan Tojnar
 - libffi-3.4.4 (mit) maintained by Matthew Bauer
 - perl5.38.2-Test-Fatal-0.017 (artistic1, gpl1Plus) maintained by nobody
 - gcc-13.2.0 (gpl3Plus) maintained by Patrick Hilhorst, Vladimír Čunát, John Ericson
 - libnetfilter_conntrack-1.0.9 (gpl2Plus) maintained by nobody
 - shadow-4.14.2 (bsd3) maintained by nobody
 - util-linux-minimal-2.39.3 (gpl2Only, gpl2Plus, gpl3Plus, lgpl21Plus, bsd3, bsdOriginalUC, publicDomain) maintained by nobody
 - zstd-1.5.5 (bsd3) maintained by Orivej Desh
 - libyaml-0.2.5 (mit) maintained by nobody
 - db-4.8.30 (sleepycat) maintained by nobody
 - json-c-0.17 (mit) maintained by Jason O'Conal
 - avahi-0.8 (lgpl2Plus) maintained by Jason O'Conal, Robin Gloster
 - libXfixes-6.0.1 (no license) maintained by nobody
 - libsoup-2.74.3 (lgpl2Plus) maintained by Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey, Jason O'Conal, Michael Raskin
 - libapparmor-3.1.6 (gpl2Only, lgpl21Only) maintained by Julien Moutinho, Austin Seipp, Andreas Schrägle, Janne Heß
 - cups-2.4.7 (asl20) maintained by Matthew Bauer
 - wayland-1.22.0 (mit) maintained by Michael Weiss, Cody Opel, Alyssa Ross
 - libXrandr-1.5.4 (no license) maintained by nobody
 - cryptsetup-2.6.1 (gpl2) maintained by Ryan Lahfa
 - nghttp2-1.57.0 (mit) maintained by Renaud
 - file-5.45 (bsd2) maintained by Doron Behar
 - gtk+3-3.24.39 (lgpl2Plus) maintained by Michael Raskin, Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey
 - giflib-5.2.1 (mit) maintained by 
 - gmp-with-cxx-6.3.0 (lgpl3Only, gpl2Only) maintained by Rahul Gopinath
 - libselinux-3.3 (gpl2Plus) maintained by 
 - freetype-2.13.2 (gpl2Plus) maintained by Thomas Tuegel
 - graphite2-1.3.14 (lgpl21) maintained by Michael Raskin
 - bash-5.2-p21 (gpl3Plus) maintained by Will Dietz
 - perl5.38.2-Net-HTTP-6.23 (artistic1, gpl1Plus) maintained by nobody
 - xkeyboard-config-2.40 (no license) maintained by nobody
 - audit-3.1.2 (gpl2Plus) maintained by Anderson Torres
 - libXrender-0.9.11 (no license) maintained by nobody
 - gnum4-1.4.19 (gpl3Plus) maintained by nobody
 - libdeflate-1.19 (mit) maintained by Orivej Desh, Dmitry Bogatov
 - perl5.38.2-HTTP-Cookies-6.10 (artistic1, gpl1Plus) maintained by nobody
 - fribidi-1.0.13 (lgpl21) maintained by nobody
 - libfido2-1.14.0 (bsd2) maintained by Will Dietz, Pavol Rusnak
 - libuv-1.47.0 (mit, isc, bsd2, bsd3, cc-by-40) maintained by Mario Rodas
 - python3-3.11.7 (psfl) maintained by Frederik Rietdijk
 - xgcc-13.2.0 (gpl3Plus) maintained by Patrick Hilhorst, Vladimír Čunát, John Ericson
 - libmnl-1.0.5 (lgpl21Plus) maintained by nobody
 - util-linux-minimal-2.39.3 (gpl2Only, gpl2Plus, gpl3Plus, lgpl21Plus, bsd3, bsdOriginalUC, publicDomain) maintained by nobody
 - libthai-0.1.29 (lgpl21Plus) maintained by 
 - gawk-5.2.2 (gpl3Plus) maintained by 
 - libXmu-1.1.4 (no license) maintained by nobody
 - unbound-1.19.0 (bsd3) maintained by Andreas Schrägle, Janne Heß
 - perl5.38.2-HTTP-Message-6.45 (artistic1, gpl1Plus) maintained by nobody
 - libbpf-1.3.0 (lgpl21, bsd2) maintained by Austin Seipp, Vladimír Čunát, Sascha Grunert, Dominique Martinet
 - pixman-0.42.2 (mit) maintained by nobody
 - libXft-2.3.8 (no license) maintained by nobody
 - libGL-1.7.0 (mit, bsd1, bsd3, gpl3Only, asl20) maintained by nobody
 - firefox-121.0.1 (mpl20) maintained by Bernardo Meurer, Martin Weinelt
 - util-linux-minimal-2.39.3 (gpl2Only, gpl2Plus, gpl3Plus, lgpl21Plus, bsd3, bsdOriginalUC, publicDomain) maintained by nobody
 - perl5.38.2-Clone-0.46 (artistic1, gpl1Plus) maintained by nobody
 - iptables-1.8.10 (gpl2) maintained by Franz Pletz
 - libssh2-1.11.0 (bsd3, libssh2) maintained by Sandro Jäckel
 - systemd-minimal-254.6 (lgpl21Plus) maintained by Florian Klink, Finn Behrens
 - icu4c-73.2 (no license) maintained by Michael Raskin
 - pango-1.51.0 (lgpl2Plus) maintained by Michael Raskin, Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey
 - libmicrohttpd-0.9.71 (lgpl2Plus) maintained by Eelco Dolstra, Rahul Gopinath, Franz Pletz
 - libcbor-unstable-2023-01-29 (mit) maintained by Will Dietz
 - attr-2.5.1 (gpl2Plus) maintained by nobody
 - perl5.38.2-HTML-Parser-3.81 (artistic1, gpl1Plus) maintained by nobody
 - libSM-1.2.4 (no license) maintained by nobody
 - libpng-apng-1.6.40 (libpng2) maintained by Vladimír Čunát
 - glib-2.78.3 (lgpl21Plus) maintained by Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey, Jason O'Conal, Michael Raskin
 - gsettings-desktop-schemas-45.0 (lgpl21Plus) maintained by Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey
 - nettle-3.9.1 (gpl2Plus) maintained by Vladimír Čunát
 - perl5.38.2-HTTP-Date-6.06 (artistic1, gpl1Plus) maintained by nobody
 - libusb-1.0.26 (lgpl21Plus) maintained by Pavol Rusnak, Ido Samuelson
 - libargon2-20190702 (asl20, cc0) maintained by Taeer Bar-Yam, Owen Lynch
 - brotli-1.1.0 (mit) maintained by freezeboy
 - glibc-2.38-27 (lgpl2Plus) maintained by Eelco Dolstra, Maximilian Bosch, Connor Baker
 - libcap-ng-0.8.3 (lgpl21) maintained by nobody
 - libnftnl-1.2.6 (gpl2Plus) maintained by Franz Pletz, Andreas Schrägle, Janne Heß
 - libxcb-1.16 (no license) maintained by nobody
 - glibc-2.38-27 (lgpl2Plus) maintained by Eelco Dolstra, Maximilian Bosch, Connor Baker
 - libpcap-1.10.4 (bsd3) maintained by Franz Pletz
 - libXt-1.3.0 (no license) maintained by nobody
 - publicsuffix-list-unstable-2023-02-16 (mpl20) maintained by Renaud
 - libepoxy-1.5.10 (mit) maintained by Cillian de Róiste
 - libX11-1.8.7 (no license) maintained by nobody
 - keyutils-1.6.3 (gpl2Plus) maintained by nobody
 - libXcursor-1.2.1 (no license) maintained by nobody
 - fontconfig-2.14.2 (bsd2) maintained by Jan Tojnar
 - tzdata-2023d (bsd3, publicDomain) maintained by Andreas Schrägle, Franz Pletz
 - tpm2-tss-4.0.1 (bsd2) maintained by Arthur Gautier
 - libxkbcommon-1.5.0 (mit) maintained by Michael Weiss, Thomas Tuegel
 - bash-interactive-5.2-p21 (gpl3Plus) maintained by Will Dietz
 - sqlite-3.44.2 (publicDomain) maintained by Eelco Dolstra, Nicolas Pouillard
 - perl5.38.2-XML-Parser-2.46 (artistic1, gpl1Plus) maintained by nobody
 - perl5.38.2-HTTP-Daemon-6.16 (artistic1, gpl1Plus) maintained by nobody
 - getent-glibc-2.38-27 (no license) maintained by nobody
 - libcap-2.69 (bsd3) maintained by nobody
 - xz-5.4.5 (gpl2Plus, lgpl21Plus) maintained by Sander van der Burg
 - perl5.38.2-Test-Needs-0.002010 (artistic1, gpl1Plus) maintained by nobody
 - perl5.38.2-File-Listing-6.16 (artistic1, gpl1Plus) maintained by nobody
 - libdatrie-2019-12-20 (lgpl21Plus) maintained by 
 - readline-8.2p7 (gpl3Plus) maintained by Will Dietz
 - libXcomposite-0.4.6 (no license) maintained by nobody
 - perl5.38.2-IO-HTML-1.004 (artistic1, gpl1Plus) maintained by nobody
 - coreutils-9.4 (gpl3Plus) maintained by Janne Heß
 - dejavu-fonts-minimal-2.37 (free) maintained by nobody
 - glib-2.78.3 (lgpl21Plus) maintained by Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey, Jason O'Conal, Michael Raskin
 - libpsl-0.21.2 (mit) maintained by Renaud
 - libgpg-error-1.47 (lgpl2Plus) maintained by Rahul Gopinath
 - libnl-3.8.0 (lgpl21) maintained by Franz Pletz
 - openssl-3.0.12 (asl20) maintained by Markus Theil
 - pcre-8.45 (bsd3) maintained by 
 - perl5.38.2-Try-Tiny-0.31 (mit) maintained by nobody
 - libidn2-2.3.4 (lgpl3Plus, gpl2Plus, gpl3Plus) maintained by Franz Pletz
 - libtool-2.4.7 (gpl2Plus) maintained by 
 - p11-kit-0.25.3 (bsd3) maintained by nobody
 - harfbuzz-7.3.0 (mit) maintained by Eelco Dolstra
 - gnugrep-3.11 (gpl3Plus) maintained by Janne Heß, Moritz Lumme
 - zlib-1.3 (zlib) maintained by nobody
 - gnused-4.9 (gpl3Plus) maintained by Jörg Thalheim
 - libXdmcp-1.1.4 (no license) maintained by nobody
 - libnfnetlink-1.0.2 (gpl2) maintained by nobody
 - libevent-2.1.12 (bsd3) maintained by nobody
 - libICE-1.1.1 (no license) maintained by nobody
 - libmd-1.1.0 (bsd3, bsd2, isc, beerware, publicDomain) maintained by Michael Weiss
 - lvm2-2.03.22 (gpl2, bsd2, lgpl21) maintained by Michael Raskin, Andreas Schrägle, Janne Heß
 - lz4-1.9.4 (bsd2, gpl2Plus) maintained by nobody
 - glibc-2.38-27 (lgpl2Plus) maintained by Eelco Dolstra, Maximilian Bosch, Connor Baker
 - libdaemon-0.14 (lgpl2Plus) maintained by nobody
 - elfutils-0.190 (gpl2Only, lgpl3Plus, gpl3Plus) maintained by Eelco Dolstra, Ryan Burns
 - libwebp-1.3.2 (bsd3) maintained by Andreas Schrägle
 - libXi-1.8.1 (no license) maintained by nobody
 - gobject-introspection-1.78.1 (gpl2, lgpl2) maintained by Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey, Jason O'Conal, Artturi N
 - json-glib-1.8.0 (lgpl21Plus) maintained by Bobby Rong, Tor Hedin Brønner, Jan Tojnar, Daniel Șerbănescu, Maxine Aubrey
 - xz-5.4.5 (gpl2Plus, lgpl21Plus) maintained by Sander van der Burg
 - tcb-1.2 (bsd3) maintained by Yurii Izorkin
 - pcre2-10.42 (bsd3) maintained by Thomas Tuegel
 - kexec-tools-2.0.26 (gpl2) maintained by nobody
 - kmod-31 (lgpl21Plus, gpl2Plus) maintained by Artturi N
 - libunwind-1.6.2 (mit) maintained by Orivej Desh
 - perl-5.38.2 (artistic1) maintained by Eelco Dolstra
 - libseccomp-2.5.5 (lgpl21Only) maintained by Austin Seipp
 - perl5.38.2-Encode-Locale-1.05 (artistic1, gpl1Plus) maintained by nobody
 - perl5.38.2-Test-RequiresInternet-0.05 (artistic1, gpl1Plus) maintained by nobody
 - ncurses-6.4 (mit) maintained by nobody
 - zstd-1.5.5 (bsd3) maintained by Orivej Desh
 - curl-8.4.0 (curl) maintained by Jason O'Conal
 - perl5.38.2-HTTP-Negotiate-6.01 (artistic1, gpl1Plus) maintained by nobody
 - perl5.38.2-libwww-perl-6.72 (artistic1, gpl1Plus) maintained by nobody
 - systemd-254.6 (lgpl21Plus) maintained by Florian Klink, Finn Behrens
 - popt-1.19 (mit) maintained by Alyssa Ross
 - kmod-31 (lgpl21Plus, gpl2Plus) maintained by Artturi N
 - libXinerama-1.1.5 (no license) maintained by nobody
 - libgcrypt-1.10.3 (lgpl2Plus) maintained by Rahul Gopinath
 - acl-2.3.1 (gpl2Plus) maintained by nobody
 - libtasn1-4.19.0 (lgpl2Plus) maintained by nobody
 - perl5.38.2-HTML-Tagset-3.20 (artistic1, gpl1Plus) maintained by nobody
 - pcsclite-2.0.1 (bsd3) maintained by Anthony Roussel
 - libtiff-4.6.0 (libtiff) maintained by nobody
 - bzip2-1.0.8 (bsdOriginal) maintained by Jörg Thalheim
 - libbsd-unstable-2023-04-29 (beerware, bsd2, bsd3, bsdOriginal, isc, mit) maintained by Matthew Bauer
 - libkrb5-1.21.2 (mit) maintained by nobody
 - iso-codes-4.15.0 (lgpl21) maintained by nobody
 - fontconfig-2.14.2 (bsd2) maintained by Jan Tojnar
 - gzip-1.13 (gpl3Plus) maintained by nobody
 - linux-pam-1.5.2 (bsd3) maintained by nobody
 - libjpeg-turbo-2.1.5.1 (ijg) maintained by Vladimír Čunát, Cole Mickens, Kevin Amado
 - perl5.38.2-URI-5.21 (artistic1, gpl1Plus) maintained by nobody
 - dav1d-1.2.1 (bsd2) maintained by Michael Weiss
 - perl5.38.2-LWP-MediaTypes-6.04 (artistic1, gpl1Plus) maintained by nobody
 - libXau-1.0.11 (no license) maintained by nobody
```

## Nix profiles

### Switch to previous system profile

https://tldr.inbrowser.app/pages/linux/nixos-rebuild

```shell
sudo nixos-rebuild switch --rollback boot
sudo reboot
```

### List system profiles

Not sure why 432 is marked as current. It is the default generation that gets activated on next boot. The currently active generation is, however, 429.

```shell
sudo nix-env --list-generations --profile /nix/var/nix/profiles/system
```
```console
...
 428   2024-03-06 12:37:56   
 429   2024-03-07 11:27:20   
 430   2024-03-10 12:48:34   
 431   2024-03-11 11:18:57   
 432   2024-03-12 22:19:53   (current)
```

```shell
ls -l /nix/var/nix/profiles/
```
```console
lrwxrwxrwx 1 root root 43 Dez 14 12:21 default -> /nix/var/nix/profiles/per-user/root/profile
drwxr-xr-x 1 root root 16 Sep  1  2023 per-user
lrwxrwxrwx 1 root root 15 Mär 12 22:19 system -> system-432-link
...
lrwxrwxrwx 1 root root 77 Mär  6 12:37 system-428-link -> /nix/store/damngdyial0i96xa46csdqk36j2njavi-nixos-system-yodaTux-23.11pre-git
lrwxrwxrwx 1 root root 77 Mär  7 11:27 system-429-link -> /nix/store/k7c7576sz868gzjci1z6l6nzmdnpd6xr-nixos-system-yodaTux-23.11pre-git
lrwxrwxrwx 1 root root 77 Mär 10 12:48 system-430-link -> /nix/store/7468m7rgk425kb23aq222a498ynfqdkc-nixos-system-yodaTux-23.11pre-git
lrwxrwxrwx 1 root root 77 Mär 11 11:18 system-431-link -> /nix/store/r51yw36ddfxq8hdsz2mm6axpbqvjaigy-nixos-system-yodaTux-23.11pre-git
lrwxrwxrwx 1 root root 77 Mär 12 22:19 system-432-link -> /nix/store/i9pxh3ax6m0yr7xlk7y7c5xdzp74xqi4-nixos-system-yodaTux-23.11pre-git
```

The currently running system. This is the currently active generation. By comparing the store path with the above output, we see that it matches generation 429.

```shell
ls -l /run/current-system
```
```console
lrwxrwxrwx 1 root root 77 Mär  9 12:44 /run/current-system -> /nix/store/k7c7576sz868gzjci1z6l6nzmdnpd6xr-nixos-system-yodaTux-23.11pre-git
```

### Garbage collection - Keep most recent X system profiles

A NixOS config example is given in [base.nix](modules/base.nix).

```shell
sudo nix-env --delete-generations +7 --profile /nix/var/nix/profiles/system
```

### Garbage collection - Delete system profiles older than X days

* https://nixos.org/manual/nix/stable/package-management/garbage-collection.html
* https://discourse.nixos.org/t/why-doesnt-nix-collect-garbage-remove-old-generations-from-efi-menu/17592/4

A NixOS config example is given in [base.nix](modules/base.nix).

Run manually for all profiles:

```shell
sudo nix-collect-garbage --delete-older-than 14d
```

Remove leftover EFI entries of removed generations:

```shell
sudo /run/current-system/bin/switch-to-configuration boot
```

### why-depends: Why is a package/dependency installed

Usage of `why-depends`: https://github.com/tldr-pages/tldr/blob/f952fc71c2587fa13207aee278eb8795af913438/pages/common/nix3-why-depends.md

Show why the currently running NixOS system requires a certain store path.

- Example: Why is one store path required.

```shell
nix --extra-experimental-features flakes --extra-experimental-features nix-command why-depends /run/current-system /nix/store/mzx8sgjkw7x2p9alq6cgz0vcdzaqz188-openssh-9.6p1
```
```console
/nix/store/k7c7576sz868gzjci1z6l6nzmdnpd6xr-nixos-system-yodaTux-23.11pre-git
└───/nix/store/b9mbk3jvazblxfma5p2yvc9xlmvrqxx7-etc
    └───/nix/store/mzx8sgjkw7x2p9alq6cgz0vcdzaqz188-openssh-9.6p1
```

- Example: Why are any of the `ffmpeg-headless` store paths currently required?

```shell
for i in /nix/store/*ffmpeg-headless-*; do
  env PAGER=cat nix --extra-experimental-features flakes --extra-experimental-features nix-command why-depends /run/current-system "$i" 2>/dev/null
done;
```
```console
/nix/store/k7c7576sz868gzjci1z6l6nzmdnpd6xr-nixos-system-yodaTux-23.11pre-git
└───/nix/store/b9mbk3jvazblxfma5p2yvc9xlmvrqxx7-etc
    └───/nix/store/snva91gl7hlm0fsf5mg5k0prv8mwnhcv-pipewire-1.0.1
        └───/nix/store/jqlvhb8jfz43vkl14wsm88h6csmx8aia-ffmpeg-headless-6.0-lib
/nix/store/k7c7576sz868gzjci1z6l6nzmdnpd6xr-nixos-system-yodaTux-23.11pre-git
└───/nix/store/b9mbk3jvazblxfma5p2yvc9xlmvrqxx7-etc
    └───/nix/store/nhypp8f5h0xv9ar9wzbp12hzyg1vah1a-user-environment
        └───/nix/store/0df15gc1a4s98n961vdd2j1pkkckn901-resources-1.3.0
            └───/nix/store/f61vlw8ampb5nh25kvs9p7rbi3cclcr4-gtk4-4.12.5
                └───/nix/store/5r52pj0fj3b06r0qgglasfmqmsfh315q-gst-plugins-bad-1.22.9
                    └───/nix/store/dsdfn1k9hnxzdwvzirx2smfinziqc8bz-openal-soft-1.23.1
                        └───/nix/store/ci4z4i38d7akpi5fqcdr2nvd1sr30l3i-pipewire-1.0.3
                            └───/nix/store/rpnsg493xz3fjhfrlc3ifz2ln65kmi8q-ffmpeg-headless-6.1-lib
...
```

### Compare two system profiles

Get latest system profile. This is the profile (usually) being active after booting the system:

```shell
ls -1 /nix/var/nix/profiles/ | sort -t'-' -n -k2 | tail -n 1
#=> 120
```

Compare current with previous profile:

```shell
# https://discourse.nixos.org/t/how-to-know-what-nixpkgs-changes-affect-me/18142/6
prev="$(ls -r /nix/var/nix/profiles/ | grep -E 'system\-' | sed -n '2 p')"
curr=/nix/var/nix/profiles/system
nix --extra-experimental-features nix-command store diff-closures /nix/var/nix/profiles/"${prev}" "${curr}"
```

```shell
# https://stackoverflow.com/a/36641298
prev="$(ls -1 /nix/var/nix/profiles/ | sort -t'-' -n -k2 | tail -n 2 | head -n 1)"
curr="$(ls -1 /nix/var/nix/profiles/ | sort -t'-' -n -k2 | tail -n 1)"
nix --extra-experimental-features nix-command store diff-closures /nix/var/nix/profiles/"${prev}" /nix/var/nix/profiles/"${curr}"
```

Compare two arbitrary system profiles:

```shell
nix --extra-experimental-features nix-command store diff-closures /nix/var/nix/profiles/system-110-link /nix/var/nix/profiles/system-116-link
```
```
cpupower: 6.1.47 → 6.1.51
element-desktop: 1.11.38 → 1.11.40, +2218.9 KiB
element-web: 1.11.38 → 1.11.40, -73.1 KiB
exempi: 2.6.3 → 2.6.4
firefox: 116.0.3 → 117.0
firefox-unwrapped: 116.0.3 → 117.0, -292.6 KiB
gnome-shell-extension-openweather: ∅ → 121, +590.5 KiB
hm_fontconfigconf.d10hmfonts.conf: ∅ → ε
initrd: ∅ → ε
initrd-linux: 6.1.47 → 6.1.51
libcap: 2.68 → 2.69
linux: 6.1.47, 6.1.47-modules → 6.1.51, 6.1.51-modules, -11.8 KiB
meld: ∅ → 3.22.0, +3858.5 KiB
net-snmp: 5.9.3 → 5.9.4
nixos-system-yodaTab: 23.05.3085.2ab91c8d65c0 → 23.05.3242.da5adce0ffaf
openjdk: +19.5 KiB
python3.10-pygobject: +27.0 KiB
stage: ∅ → 1-init.sh, +29.5 KiB
tor-browser-bundle-bin: 12.5.2 → 12.5.3, +18.1 KiB
user: +2885.0 KiB
```

## NixOS configuration debugging

* https://nixos.wiki/wiki/Nix_command/repl

Evaluating parts of the configuration.

First, start `nix repl`:

```shell
nix repl --file '<nixpkgs/nixos>' -I nixos-config=hosts/$(hostname)/configuration.nix
```

Example: `config.home-manager`

```shell
config.home-manager.
# Press `TAB`
#=> config.home-manager.backupFileExtension  config.home-manager.useUserPackages
#=> config.home-manager.extraSpecialArgs     config.home-manager.users
#=> config.home-manager.sharedModules        config.home-manager.verbose
#=> config.home-manager.useGlobalPkgs
```

Example: The `home` variable:

```shell
config.home-manager.users.yoda.home
```

Example: The value of one config option

```shell
# The following option is set to `"${config.xdg.dataHome}/.histfile";`
# where `config` is the Home Manager configuration.

config.home-manager.users.yoda.programs.zsh.history.path
#=> "/home/yoda/.local/share/.histfile"
```

## Show Nix configuration

* https://nixos.org/manual/nix/stable/command-ref/new-cli/nix3-show-config.html

```shell
nix --extra-experimental-features nix-command show-config
```

## Evaluate NixOS configuration to JSON

See also section "NixOS Configuration Debugging"!

* https://discourse.nixos.org/t/can-i-run-nix-instantiate-eval-strict-on-my-configuration-nix/7105/4

This evaluates `configuration.nix` (single module):

```shell
NIXPKGS_ALLOW_UNFREE=1 nix-instantiate --strict --json --eval -E '
import ./hosts/yodaTab/configuration.nix  {
  config = {};
  pkgs = import <nixpkgs> {};
  lib = import <nixpkgs/lib>;
}
' > evaluated-config.json
```

Then open `evaluated-config.json`.

## Evaluate expressions in the context of a NixOS configuration managed with Colmena

https://colmena.cli.rs/unstable/reference/cli.html#colmena-eval

Either specify a file containing the expression or add it as argument with `-E`.

```shell
colmena eval -E '{ nodes, lib, pkgs, ... }: nodes.yodaTux.config.networking.hostName'
```

```shell
nix-shell -p jq
colmena eval -E '{ nodes, lib, pkgs, ... }: nodes.yodaTux.config.environment.systemPackages' | jq
```

```shell
colmena eval -E '{ nodes, lib, pkgs, ... }: pkgs.linux' 
#=> "/nix/store/bmyh7a4j9xim7xxc5x1qk1qvlb2y7186-linux-6.6.48"
```

```shell
colmena eval -E '{ nodes, lib, pkgs, ... }: pkgs.linuxPackages.kernel'  
#=> "/nix/store/bmyh7a4j9xim7xxc5x1qk1qvlb2y7186-linux-6.6.48"
colmena eval -E '{ nodes, lib, pkgs, ... }: pkgs.linuxPackages_latest.kernel'
#=> "/nix/store/n0csng9aw5nhpll1m5rbvvxkkj2j63px-linux-6.10.7"
```

## Evaluate expressions

* https://discourse.nixos.org/t/eval-nix-expression-from-the-command-line/8993/6

```shell
nix-instantiate --eval -E 'with import <nixpkgs> { }; vscode.version'
#=> "1.78.2"
```

Shell wrapper:

```shell
nix-eval() { nix-instantiate --eval -E "with import <nixpkgs> {}; ${*}"; }
```

Examples:

```shell
nix-eval 'vscode.version'
#=> "1.78.2"
nix-eval 'lib.forEach [ 1 2 ] (x: toString x)'
#=> [ "1" "2" ]
nix-eval 'lib.head [1 2]'
#=> 1
nix-eval 'lib.head (
  lib.forEach [ 1 2 ] (x: toString x)
)'
#=> "1"
nix-eval 'lib.head (
  lib.forEach [ {a=1;} {a=2;} ] (x: x.a)
)'
#=> 1
nix-eval 'lib.attrsets.mergeAttrsList [{a=1;} {b=2;}]'
#=> { a = 1; b = 2; }
nix-eval '{ a=1; }.b or 2'
#=> 2
nix-eval '{ a=false; }.a or true'
#=> false
nix-eval '{ a=1; }?a'
#=> true
nix-eval 'with lib.strings; concatMapStrings (x: " -a " + x + " -i 600") ["sda" "sdc"]'
#=> " -a sda -i 600 -a sdc -i 600"
```

## Escape strings

* https://nixos.org/manual/nix/stable/language/values

Double-quoted strings (e.g. `"foo bar"`):
```
"  -> \"
\  -> \\
${ -> \${
```

Indented strings (e.g. `''foo bar''`):
* `${` -> `''${`
* `''` -> `'''`

URIs can be written without quotes (e.g. `http://example.org/foo.bar`).

## Run AppImages

* https://nixos.wiki/wiki/Appimage

```shell
# Note how your shell prefix changes.
nix-shell -p appimage-run
```
```shell
# Inside the shell, you can run an AppImage:
appimage-run ~/Downloads/ubports-installer_0.10.0_linux_x86_64.AppImage
```

See the [binfmt option](https://nixos.org/manual/nixos/stable/options#opt-programs.appimage.binfmt) to e.g. run AppImages of other processor architectures.

## Audio troubleshooting - Realtek ALC898 Audio Codec on ASRock Z77 Extreme 4

TODO: I couldn't get the onboard audio to work.

- https://discourse.nixos.org/t/fixing-audio-on-asus-strix-scar-17-g733qs/12687
- https://bbs.archlinux.org/viewtopic.php?id=147242
- https://en.opensuse.org/SDB:Audio_troubleshooting#Script_to_run_to_obtain_detailed_information
- https://nixos.wiki/wiki/ALSA#Other_hardware_specific_problems
- https://bbs.archlinux.org/viewtopic.php?pid=1452128#p1452128

`aplay -L`
```console
null
    Discard all samples (playback) or generate zero samples (capture)
pipewire
    PipeWire Sound Server
default
    Default ALSA Output (currently PipeWire Media Server)
hdmi:CARD=HDMI,DEV=0
    HDA ATI HDMI, HDMI 0 *
    HDMI Audio Output
hdmi:CARD=HDMI,DEV=1
    HDA ATI HDMI, HDMI 1
    HDMI Audio Output
hdmi:CARD=HDMI,DEV=2
    HDA ATI HDMI, HDMI 2
    HDMI Audio Output
hdmi:CARD=HDMI,DEV=3
    HDA ATI HDMI, HDMI 3
    HDMI Audio Output
hdmi:CARD=HDMI,DEV=4
    HDA ATI HDMI, HDMI 4
    HDMI Audio Output
hdmi:CARD=HDMI,DEV=5
    HDA ATI HDMI, HDMI 5
    HDMI Audio Output
```

`cat /proc/asound/cards`
```console
 0 [HDMI           ]: HDA-Intel - HDA ATI HDMI
                      HDA ATI HDMI at 0xf7b60000 irq 40
```

`lspci -vnn | grep -A1 -i audio`
```console
00:1b.0 Audio device [0403]: Intel Corporation 7 Series/C216 Chipset Family High Definition Audio Controller [8086:1e20] (rev 04)
        Subsystem: ASRock Incorporation Z77 Extreme4 motherboard [1849:1898]
--
01:00.1 Audio device [0403]: Advanced Micro Devices, Inc. [AMD/ATI] Tahiti HDMI Audio [Radeon HD 7870 XT / 7950/7970] [1002:aaa0]
        Subsystem: Advanced Micro Devices, Inc. [AMD/ATI] Tahiti HDMI Audio [Radeon HD 7870 XT / 7950/7970] [1002:aaa0]
        Flags: bus master, fast devsel, latency 0, IRQ 40
```

`sudo lspci -vnn`
```console
00:1b.0 Audio device [0403]: Intel Corporation 7 Series/C216 Chipset Family High Definition Audio Controller [8086:1e20] (rev 04)
        Subsystem: ASRock Incorporation Z77 Extreme4 motherboard [1849:1898]
        Flags: fast devsel, IRQ 22
        Memory at f7c10000 (64-bit, non-prefetchable) [size=16K]
        Capabilities: [50] Power Management version 2
        Capabilities: [60] MSI: Enable- Count=1/1 Maskable- 64bit+
        Capabilities: [70] Express Root Complex Integrated Endpoint, MSI 00
        Capabilities: [100] Virtual Channel
        Capabilities: [130] Root Complex Link
        Kernel modules: snd_hda_intel
```

## Graphic drivers

Usually most of this should work out of the box on NixOS.

Vulkan:
- Verification:
  - If `vulkaninfo` returns information about your GPU, Vulkan is working. https://wiki.archlinux.org/title/Vulkan#Verification
  - Run `vkcube` (X11) or `vkcube-wayland` (Wayland). It should view a spinning 3D cube and output e.g. `Selected GPU 0: AMD Radeon Graphics (RADV RENOIR)`

OpenGL:
- Verification: https://wiki.archlinux.org/title/OpenGL#Verification
  - `eglinfo -B` should not return `eglInitialize failed`
  - `eglgears_x11` and `eglgears_wayland` -> ![eglgears.png](assets/doc/eglgears.png)

Video acceleration:
- VA-API
  - Verifying: `vainfo` -> E.g. `Driver version: Mesa Gallium driver 23.1.9 for AMD Radeon Graphics`. https://wiki.archlinux.org/title/Hardware_video_acceleration#Verifying_VA-API
  - Driver comparison chart. https://wiki.archlinux.org/title/Hardware_video_acceleration#VA-API_drivers
    - With `libva-mesa-driver` on "Radeon RX 7900 and higher/newer" a codec for encoding AV1 8 and 10 bit is available.
- VDPAU
  - Video Decode and Presentation API for Unix (VDPAU).
  - Verifying: `vdpauinfo`. https://wiki.archlinux.org/title/Hardware_video_acceleration#Verifying_VDPAU

Verify video driver in use:
- `lspci -k | grep -EA3 'VGA|3D|Display'`. Example: `Kernel driver in use: amdgpu`

Verification in general:
- Encode a video or play a game and watch AMD GPU usage with `radeontop`.

Configuration example to disable integrated GUP: See [./hosts/yodaGaming/configuration.nix](./hosts/yodaGaming/configuration.nix)

Configuration example for an AMD GPU (https://github.com/tolgaerok/nixos-kde/blob/main/core/gpu/amd/default.nix): See [./modules/gpu-amd.nix](./modules/gpu-amd.nix)

## XDG mimes, desktop files

Desktop files:
- `/run/current-system/sw/share/applications`
- `/etc/profiles/per-user/yoda/share/applications/`

Both above sub-paths are part of the `XDG_DATA_DIRS` variable:
- `echo $XDG_DATA_DIRS | grep /run/current-system/sw/share`
- `echo $XDG_DATA_DIRS | grep /etc/profiles/per-user/yoda/share`

List default apps and the associated handlers:

```shell
handlr list
```
```console
┌────────────────────────────────┬─────────────────────────────────────────┐
│ application/octet-stream       │ thunderbird.desktop                     │
│ ...                            │                                         │
│ x-scheme-handler/sgnl          │ signal-desktop.desktop                  │
└────────────────────────────────┴─────────────────────────────────────────┘
```

Set default handler for mime/extension:

```shell
handlr set text/html re.sonny.Junction.desktop
```

Open any URI with `handlr`:

```shell
handlr open https://wikipedia.org
```

Open any URI with `gio`, part of `glib`:

```shell
gio open https://wikipedia.org
```

- Note: `gio open` does not follow the XDG spec. https://discourse.nixos.org/t/configure-how-xdg-open-opens-html-files/6419/23

Further examples:

```shell
xdg-settings get default-web-browser
#=> re.sonny.Junction.desktop
xdg-mime query default x-scheme-handler/http and x-scheme-handler/https
#=> re.sonny.Junction.desktop
xdg-mime query default text/html
#=> firefox.desktop
```

## Additional resources

* Simple NixOS flake template for NixOS with HomeManager. https://github.com/Misterio77/nix-starter-configs#readme
* NixOS guide (development environment, gaming, etc). https://github.com/mikeroyal/NixOS-Guide#table-of-contents
* nix function cheatsheet: https://nix-cheatsheet.pixie.homes/
* Documenting the Journey of Learning and Mastering Nix. https://ianthehenry.com/posts/how-to-learn-nix/
* Nix language basics. https://nix.dev/tutorials/nix-language.html
* Nix data types. https://nixos.org/manual/nix/stable/language/values
* MkIfElse. https://discourse.nixos.org/t/mkif-vs-if-then/28521/4
* Nix language basics - a one-pager. https://github.com/tazjin/nix-1p#nix---a-one-pager

### Nix Pills

* https://nixos.org/guides/nix-pills/pr01

It provides a tutorial introduction into the Nix package manager and Nixpkgs package collection, in the form of short
chapters called 'pills'.

### Papers

Papers about Nix:

* The Purely Functional Software Deployment Model (2006). http://nixos.org/~eelco/pubs/phd-thesis.pdf, https://edolstra.github.io/pubs/phd-thesis.pdf, https://github.com/edolstra/edolstra.github.io/blob/master/pubs/phd-thesis.pdf
  * May 2023: Some insights from the thesis in short form. https://jonathanlorimer.dev/posts/nix-thesis.html
* NixOS: A Purely Functional Linux Distribution (2008): https://github.com/edolstra/edolstra.github.io/blob/master/pubs/nixos-icfp2008-final.pdf, https://github.com/edolstra/edolstra.github.io/blob/master/pubs/nixos-jfp-final.pdf
* Nix: A Safe and Policy-Free System for Software Deployment (2004): https://edolstra.github.io/pubs/nspfssd-lisa2004-final.pdf
