about summary refs log tree commit diff stats
path: root/modules/by-name/ni/nixos-shell/nixos-shell.sh
blob: 390e60b1446903d9a85e1e90ae6efe57c9c739ae (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env dash

# nixos-config - My current NixOS configuration
#
# Copyright (C) 2025 Jörg Thalheim and contributors
# SPDX-License-Identifier: MIT
#
# This file is part of my nixos-config.
#
# You should have received a copy of the License along with this program.
# If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

SHARED_DIR="$(mktemp --directory)"
cleanup() {
    rm --recursive "$SHARED_DIR"
}
trap cleanup EXIT
export SHARED_DIR

TMPDIR="$SHARED_DIR"
export TMPDIR

cat <<EOF >"$SHARED_DIR/.env_variables"
{
    "pwd": "$PWD",
    "term": "$TERM",
    "path": "$PATH"
}
EOF

mk_tag() {
    additional_path="$1"

    # tags must be shorter than 32 bytes
    # and must not begin with a digit.
    {
        printf "a"
        echo "$additional_path" | sha256sum | head -c 30
    }
}

for raw_additional_path in "$@"; do
    additional_path="$(realpath "$raw_additional_path")"
    tag="$(mk_tag "$additional_path")"

    if [ "$(jq --arg mount "$tag" '.mount.[$mount]' "$SHARED_DIR/.env_variables")" != "null" ]; then
        echo "Path '$additional_path' alread added."
        shift 1
        continue
    fi

    jq --arg mount "$tag" --arg target "$additional_path" \
        '. + {mount: {$mount: $target}}' "$SHARED_DIR/.env_variables" | sponge "$SHARED_DIR/.env_variables"

    set -- "$@" -virtfs "local,path=$additional_path,security_model=none,readonly=on,mount_tag=$tag"
    shift 1
done

# Do not exec here, as we don't want to lose our cleanup hooks.
"run-$HOST_NAME-vm" "$@"