Created
August 24, 2019 15:20
-
-
Save srhb/a87c94a9da6b50586356b83b3fc20440 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ lib, pkgs, config, ... }: | |
let | |
cfg = config.services.nixos-rollback; | |
get-system-generation = pkgs.writeShellScriptBin "get-system-generation" '' | |
#!${pkgs.stdenv.shell} | |
set -euo pipefail | |
/var/run/current-system/sw/bin/nix-env --list-generations --profile /nix/var/nix/profiles/system | ${pkgs.gnugrep}/bin/grep current | ${pkgs.gawk}/bin/awk '{print $1}' | |
''; | |
stop-nixos-rollback = pkgs.writeShellScriptBin "stop-nixos-rollback" '' | |
#!${pkgs.stdenv.shell} | |
set -euo pipefail | |
ROLLBACK_FILE=${cfg.path} | |
CURRENT_GENERATION=$(${get-system-generation}/bin/get-system-generation) | |
echo Setting "$ROLLBACK_FILE" to "$CURRENT_GENERATION". | |
echo "$CURRENT_GENERATION" > "$ROLLBACK_FILE" | |
''; | |
in | |
{ | |
options.services.nixos-rollback = { | |
enable = lib.mkEnableOption "nixos-rollback"; | |
path = lib.mkOption { | |
type = lib.types.path; | |
default = "/nix/var/nix/rollback-generation"; | |
description = "Path to the desired rollback generation"; | |
}; | |
}; | |
config = lib.mkIf cfg.enable { | |
environment.systemPackages = [ | |
get-system-generation | |
stop-nixos-rollback | |
]; | |
systemd.services.nixos-rollback = { | |
path = [ get-system-generation stop-nixos-rollback ]; | |
script = '' | |
if [ ! -f ${cfg.path} ]; then | |
echo Rollback file "${cfg.path}" does not exist. | |
stop-nixos-rollback | |
fi; | |
if [[ $(get-system-generation) > $(cat ${cfg.path}) ]]; then | |
/var/run/current-system/sw/bin/nixos-rebuild switch --rollback | |
fi; | |
''; | |
}; | |
systemd.timers.nixos-rollback = { | |
wantedBy = [ "timers.target" ]; | |
timerConfig = { | |
OnActiveSec = "15 min"; | |
OnUnitInactiveSec = "15 min"; | |
}; | |
}; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment