nixos-config/modules/environment/user-impermanence.nix

95 lines
2.9 KiB
Nix
Raw Normal View History

2024-11-02 13:24:01 +00:00
{
config,
lib,
2024-11-03 09:56:04 +00:00
pkgs,
2024-11-03 12:32:18 +00:00
inTester,
2024-11-02 13:24:01 +00:00
...
}:
with lib; {
options = {
environment.impermanence.users = mkOption {
description = "Which users to clean up the home directory for";
default = [];
type = types.listOf types.str;
};
};
2024-11-03 12:32:18 +00:00
config = mkIf (config.environment.impermanence.enable && config.environment.impermanence.users != []) {
2024-11-05 13:39:51 +00:00
programs.fuse.userAllowOther = true;
2024-11-03 12:18:10 +00:00
home-manager.users = listToAttrs (map (name: {
inherit name;
value.home.persistence.default = {
persistentStoragePath = "/persistent/home/${name}";
2024-11-03 14:51:26 +00:00
allowOther = true;
2024-11-03 12:18:10 +00:00
};
})
config.environment.impermanence.users);
2024-11-02 13:24:01 +00:00
systemd.services = listToAttrs (flatten (map (name: let
cfg = config.users.users.${name};
in [
{
name = "cleanup-home-${name}";
description = "Clean home directory for ${name}";
value = {
wantedBy = [
"user@${toString cfg.uid}.service"
"multi-user.target"
2024-11-02 13:24:01 +00:00
];
before = [
"user@${toString cfg.uid}.service"
2024-11-02 13:25:15 +00:00
"home-manager-${name}.service"
2024-11-02 13:24:01 +00:00
];
2024-11-03 08:10:25 +00:00
partOf = [
"user@${toString cfg.uid}.service"
];
2024-11-02 13:24:01 +00:00
serviceConfig.Type = "oneshot";
script = ''
if [[ -e ${cfg.home} ]]; then
timestamp=$(date --date="@$(stat -c %X ${cfg.home})" "+%Y-%m-%d_%H:%M:%S")
2024-11-02 13:47:17 +00:00
mkdir -p /persistent/old-homedirs/${name}
2024-11-03 08:05:13 +00:00
mv ${cfg.home} /persistent/old-homedirs/${name}/$timestamp
2024-11-02 13:24:01 +00:00
fi
delete_subvolume_recursively() {
IFS=$'\n'
for i in $(btrfs subvolume list -o "$1" | cut -f 9- -d ' '); do
delete_subvolume_recursively "/persistent/old-homedirs/${name}/$i"
done
2024-11-03 09:56:04 +00:00
${pkgs.btrfs-progs}/bin/btrfs subvolume delete "$1"
2024-11-02 13:24:01 +00:00
}
for i in $(find /persistent/old-homedirs/${name} -maxdepth 1 -mtime +30); do
delete_subvolume_recursively "$i"
done
2024-11-03 09:56:04 +00:00
${pkgs.btrfs-progs}/bin/btrfs subvolume create ${cfg.home}
2024-11-05 12:25:14 +00:00
chown -R ${name}:${cfg.group} ${cfg.home}
mkdir -p /persistent/home/${name}
chown -R ${name}:${cfg.group} /persistent/home/${name}
2024-11-02 13:24:01 +00:00
'';
};
}
{
name = "home-manager-${name}";
value = {
wantedBy = mkForce [
"user@${toString cfg.uid}.service"
"multi-user.target"
2024-11-02 13:24:01 +00:00
];
after = [
"cleanup-home-${name}.service"
];
before = [
"user@${toString cfg.uid}.service"
2024-11-02 13:24:01 +00:00
];
2024-11-03 08:10:25 +00:00
partOf = [
"user@${toString cfg.uid}.service"
];
2024-11-02 13:24:01 +00:00
};
}
])
config.environment.impermanence.users));
};
}