aboutsummaryrefslogtreecommitdiff
path: root/hosts/sagittarius/auto-update.nix
blob: 4e8c2ac5a6c05a3add9d150229cc48eb9992200c (plain)
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
{ pkgs, ... }:
let
  configRepoSource = "file:///var/lib/git/repos/isabella/nixos-config";
in
{
  systemd.timers.auto-update-nixos = {
    enable = true;
    description = "Timer that automatically fetches and updates the NixOS config.";
    timerConfig = {
      Unit = "update-nixos.service";
      OnUnitActiveSec = "60s";
    };
    wantedBy = [ "mutli-user.target" ];
  };

  systemd.services.update-nixos = {
    enable = true;
    description = "Services that fetches and updates the NixOS config.";
    serviceConfig = {
      Type = "oneshot";
      User = "root";
      StandardOutput = "journal";
      StandardError = "journal";
    };
    path = [ pkgs.gitMinimal pkgs.nixos-rebuild-ng ];
    # we need root privileges for a system update anyway
    confinement.enable = false;

    enableStrictShellChecks = true;
    script = ''
      #!/bin/sh
      set -xeu

      SRCREPO="$1"
      if [ -z "$SRCREPO" ]; then
        echo "Error: git repository source was not provided." >&2
        exit 1
      fi

      TEMPDIR="$(mktemp --directory)"
      git clone --depth 1 "$SRCREPO" "$TEMPDIR"

      pushd "$TEMPDIR"

      TAGS="$(git tag --sort tag --list 'v*')"
      LATESTTAG="$(echo "$TAGS" | head --lines 1)"

      if [ -z "$LATESTTAG" ]; then
        echo "Error: no release tags defined." >&2
        exit 1
      fi

      git fetch "$SRCREPO" "$LATESTTAG"
      git checkout FETCH_HEAD

      nixos-rebuild switch --flake .#

      popd

      rm -rf "$TEMPDIR"
    '';
    scriptArgs = "${configRepoSource}";
  };
}