Scripts to (interactively) demonstrate capabilities of Nix. Mirror of https://gitlab.com/SFrijters/nix-container-demo
#!/usr/bin/env bash

set -Eeuo pipefail

source "$(dirname "${BASH_SOURCE[0]}")/bash/nix-container-demo-helper.sh"

lint() {
    local -r shellcheck_cmd="nix run ${NIXPKGS_FLAKEREF}#shellcheck -- -S style -x"
    local f
    for f in $(find "$(dirname "${BASH_SOURCE[0]}")" -name '*.sh' | sort); do
        echo "${f}"
        ${shellcheck_cmd} "${f}" || return 1
    done
}

run() {
    if [ "${WRAP_NIX_MAKE_GCROOTS:-0}" = 1 ]; then
        __nix_make_gcroot "$(nix flake metadata "${NIXPKGS_FLAKEREF}" | grep 'Path' | awk '{ print $2; }')"
    fi
    local f
    for f in $(find "$(dirname "${BASH_SOURCE[0]}")" -name 'demo.sh' | sort); do
        democlear
        demoheader "$(dirname "${f}" | sed 's|^\./||')"
        "${f}"
        demoheader "All done with this part!"
        demopause
    done
}

usage() {
    echo "$0: run all 'demo.sh' scripts in order"
    echo "  -h|--help|-?: Show usage"
    echo "  -a|--auto: run in automatic mode (no pausing)"
    echo "  -g|--gcroots <create|delete|recreate|print>: (re)create, delete, or print Nix garbage collector roots for nix build/run/develop outputs"
    echo "  -l|--lint: run linter on shell files"
}

do_lint=0
do_interactive=1
nix_gcroots_action=

while [[ $# -gt 0 ]]; do
  case $1 in
      -a|--auto)
          do_interactive=0
          shift
          ;;
      -g|--gcroots)
          if [ "${2:-}" = create ] || [ "${2:-}" = delete ] || [ "${2:-}" = recreate ] || [ "${2:-}" = print ]; then
              nix_gcroots_action=$2
          else
              echo "Unknown or missing --gcroots option '${2:-}'"
              exit 1
          fi
          shift
          shift
          ;;
      -h|--help|-\?)
          usage
          exit 0
          ;;
      -l|--lint)
          do_lint=1
          shift
          ;;
      -*)
          echo "Unknown option $1"
          exit 1
          ;;
      *)
          POSITIONAL_ARGS+=("$1")
          shift
          ;;
  esac
done

if [ "${do_lint}" = 1 ]; then
    lint || exit 1
else
    do_nix_make_gcroots=0
    if [ "${nix_gcroots_action}" = delete ]; then
        __nix_clean_gcroots
        exit 0
    elif [ "${nix_gcroots_action}" = print ]; then
        __nix_print_gcroots
        exit 0
    elif [ "${nix_gcroots_action}" = recreate ]; then
        __nix_clean_gcroots
        do_nix_make_gcroots=1
    elif [ "${nix_gcroots_action}" = create ]; then
        do_nix_make_gcroots=1
    fi
    WRAP_NIX_MAKE_GCROOTS="${do_nix_make_gcroots}" LIBDEMO_INTERACTIVE="${do_interactive}" run
    if [ "${nix_gcroots_action}" = create ] || [ "${nix_gcroots_action}" = recreate ]; then
        __nix_print_gcroots
    fi
fi