Scripts to (interactively) demonstrate capabilities of Nix. Mirror of https://gitlab.com/SFrijters/nix-container-demo
#!/usr/bin/env bash
# shellcheck disable=SC1010,SC2288
set -Eeuo pipefail

dir="$(realpath --relative-to="${PWD}" "$(dirname "${BASH_SOURCE[0]}")")"

source "${dir}/../bash/nix-container-demo-helper.sh"

h "Adding CMake"

n "The more we offload to 'classic' tools, the easier it is to also build without Nix."
, "This makes it an easier sell to use in most cases; other people are not forced to use it,"
, "but can use the shared build system in their own environment if so desired."
, "Packaging in this way and making use of the sandboxed Nix build process"
, "can help find dependencies that were not correctly declared etc."
x bat "${dir}/../src/CMakeLists.txt"

n "If we add a proper build system like CMake, the Nix part of building a package gets even easier:"

x bat "${dir}/wttr-delft.nix"

x nix build "${dir}" -L

h "Cross-compilation"
, "The previous build was for x86_64-linux by default because that is our current system:"
x file ./result/bin/wttr-delft

h "We can very easily set up cross-compilation:"
, "We use the 'flake-utils' library to abstract away some of the complications in the flake:"
, "This also demonstrates how easy it is to combine flakes."
x bat "${dir}/flake.nix"

, "Now we can call a different output:"
x nix build "${dir}#cross-riscv64" -L
, "And this is indeed a RISC-V binary:"
x file ./result/bin/wttr-delft

h "Static executables"
, "We can also cross compile a static build:"
x nix build "${dir}#static" -L
, "And this is indeed a static binary:"
x file ./result/bin/wttr-delft
x ls -lh ./result/bin/wttr-delft

h "Everything together"
, "Static cross compiled binary for aarch64-linux - you can copy this executable and run it on a Raspberry Pi!"
x nix build "${dir}#cross-aarch64-static" -L
x file ./result/bin/wttr-delft
x ls -lh ./result/bin/wttr-delft

if [ ! -e /proc/sys/fs/binfmt_misc/aarch64-linux ] || ! grep -q enabled /proc/sys/fs/binfmt_misc/aarch64-linux; then
    w "It seems aarch64-linux binfmt emulation is not available, the following part of the demo may not work"
fi

h "Emulation"
, "If we take a look at what the flake provides we see multiple architectures as well:"
x nix flake show "${dir}" --all-systems

n "This will not work if the emulation is not available:"
, "But, if you use NixOS it's also very simple to set up binfmt to emulate e.g. aarch64-linux!"
,
, "  boot.binfmt.emulatedSystems = [ \"aarch64-linux\" ];"

x nix build "${dir}#packages.aarch64-linux.default" -L
x file ./result/bin/wttr-delft

, "And we can actually run it as well"
x ./result/bin/wttr-delft