summaryrefslogtreecommitdiffstats
path: root/scripts/build.sh
blob: b311eb65c581538232fb5d32e6c49c4b27d51587 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#! /usr/bin/env sh
set -eu

build_system() {
    host="$1"

    show_trace_arg=""
    if [ "$show_trace" = true ]; then
        show_trace_arg="--show-trace"
    fi

    _val="$(nix build ".#nixosConfigurations.$host.config.system.build.toplevel" --print-out-paths --no-link --option max-jobs 1 $show_trace_arg)"
    exit_val="$?"

    if [ "$exit_val" -ne 0 ]; then
        echo "ERROR: Failed to build you system config for host: '$host'" 1>&2
        printf 1
    else
        printf "%s" "$_val"
    fi
}
remove_symlink() {
    link="$1"
    if [ -L "$link" ]; then
        rm "$link"
    else
        echo "ERROR: '$link' is not a symlink. Not removing it." 1>&2
        exit 1
    fi
}

root="$(git rev-parse --show-toplevel)"
use_dirty=true
show_trace=false

while [ "$#" -ne 0 ]; do
    case "$1" in
    --dirty)
        use_dirty=true
        ;;
    --clean)
        use_dirty=false
        ;;
    --show-trace)
        show_trace=true
        ;;
    --* | -*)
        echo "arg '$1' is not known."
        exit 2
        ;;
    *)
        # We reached the hosts
        break
        ;;
    esac
    shift 1
done

if [ "$#" -eq 0 ]; then
    # shellcheck disable=SC2046
    set -- $(ls "$root/hosts/by-name")
fi

if [ "$use_dirty" = "false" ]; then
    tmp="$(mktemp -d -t "server_build_script_XXXXX")"
    trap 'rm -r "$tmp"' EXIT

    git archive --format=tar.gz HEAD | {
        cd "$tmp"
        tar -xz
    }

    cd "$tmp"
fi

for host in "$@"; do
    system="$(build_system "$host")"
    [ "$system" = "1" ] && exit 1

    result_link="$root/result-$host"
    remove_symlink "$result_link"
    nix-store --add-root "$result_link" --realise "$(readlink -f "$system")"

    # Try to also provide an easy link for potential home manager outputs.
    fd "home-manager-\w*.service" "$result_link/etc/systemd/system" | while read -r hm; do
        home_generation_link="$(grep ExecStart= "$hm" | awk '{print $2}')"
        user_name="$(basename "$hm" | sed 's/home-manager-\(.*\)\.service/\1/')"
        home_link="$root/result-$host-hm-$user_name"

        remove_symlink "$home_link"
        ln --symbolic "$home_generation_link" "$home_link"
    done

    if [ "$host" = "$(hostname)" ]; then
        nvd diff /run/current-system "$result_link"
    fi
done
# vim: ft=sh