machines/nix/modules/nixos/os/auto-update/default.nix

57 lines
1.4 KiB
Nix

{
config,
lib,
inputs,
pkgs,
...
}:
let
cfg = config.khscodes.os.auto-update;
upgradePath = "/var/lib/system-upgrade";
upgradeVersion = "/var/lib/system-upgrade.version";
prepareUpgrade = pkgs.writeShellApplication {
runtimeInputs = [
pkgs.uutils-coreutils-noprefix
pkgs.nix
pkgs.git
];
name = "nixos-upgrade-prepare-flake";
text = ''
current_version=""
if [[ -f ${upgradeVersion} ]]; then
current_version="$(cat ${upgradeVersion})"
fi
if [[ "$current_version" != "${inputs.self.outPath}" ]]; then
rm -rf ${upgradePath}
cp -r ${inputs.self.outPath} ${upgradePath}
echo -n ${inputs.self.outPath} > ${upgradeVersion}
fi
cd ${upgradePath}
nix --extra-experimental-features "nix-command flakes" flake update
'';
};
in
{
options.khscodes.os.auto-update = {
enable = lib.mkEnableOption "Enables automatic OS updates";
dates = "02:00";
randomizedDelaySec = "45min";
};
config = lib.mkIf cfg.enable {
system.autoUpgrade = {
enable = true;
flake = upgradePath;
allowReboot = true;
};
systemd.services.nixos-upgrade-prepare-flake = {
wantedBy = [ "nixos-upgrade.service" ];
before = [ "nixos-upgrade.service" ];
serviceConfig = {
Type = "oneshot";
ExecStart = lib.getExe prepareUpgrade;
};
};
};
}