diff options
Diffstat (limited to 'hosts/tower/auto-update.nix')
| -rw-r--r-- | hosts/tower/auto-update.nix | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/hosts/tower/auto-update.nix b/hosts/tower/auto-update.nix new file mode 100644 index 0000000..2afa4b9 --- /dev/null +++ b/hosts/tower/auto-update.nix @@ -0,0 +1,80 @@ +{ pkgs, ... }: +let + configRepoSource = "file:///var/lib/git/repos/isabella/nixos-config"; +in +{ + systemd.timers.auto-update-nixos = { + enable = false; + description = "Fetch and update the NixOS config every minute"; + timerConfig = { + Unit = "update-nixos.service"; + OnUnitActiveSec = "60s"; + }; + wantedBy = [ "multi-user.target" ]; + }; + + systemd.services.update-nixos = { + enable = false; + description = "Fetches and update 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 -eu + + SRC_REPO="$1" + if [ -z "$SRC_REPO" ]; then + echo "Error: git repository source was not provided." >&2 + exit 1 + fi + + TEMP_DIR="$(mktemp --directory)" + git clone --depth 1 "$SRC_REPO" "$TEMP_DIR" + + pushd "$TEMP_DIR" + + TAGS="$(git tag --sort tag --list 'v*')" + LATEST_TAG="$(echo "$TAGS" | tail --lines 1)" + + if [ -z "$LATEST_TAG" ]; then + echo "Error: no release tags defined." >&2 + exit 1 + fi + + git fetch "$SRC_REPO" "$LATEST_TAG" + git checkout FETCH_HEAD + + CURRENT_REV="$(git rev-parse HEAD)" + STATE_DIR="/var/lib/auto-update" + [ -d "$STATE_DIR" ] || mkdir -p "$STATE_DIR" + + if [ -e "$STATE_DIR/last-commit" ]; then + LAST_REV="$(cat "$STATE_DIR/last-commit")" + if [ "$CURRENT_REV" = "$LAST_REV" ]; then + echo "System is already up to date. Exiting." >&2 + exit 0 + fi + fi + echo -n "$CURRENT_REV" > "$STATE_DIR/last-commit" + + nixos-rebuild switch --flake .# + + popd + + rm -rf "$TEMP_DIR" + ''; + scriptArgs = "${configRepoSource}"; + }; +} |
