# This file contains an ephemeral btrfs root configuration
# TODO: perhaps partition using disko in the future
{ lib, config, ... }:
let
  hostname = config.networking.hostName;
  wipeScript = ''
    mkdir /tmp -p
    MNTPOINT=$(mktemp -d)
    (
      mount -t btrfs -o subvol=/ /dev/disk/by-label/${hostname} "$MNTPOINT"
      trap 'umount "$MNTPOINT"' EXIT

      echo "Creating needed directories"
      mkdir -p "$MNTPOINT"/persist/var/{log,lib/{nixos,systemd}}

      echo "Cleaning root subvolume"
      btrfs subvolume list -o "$MNTPOINT/root" | cut -f9 -d ' ' |
      while read -r subvolume; do
        btrfs subvolume delete "$MNTPOINT/$subvolume"
      done && btrfs subvolume delete "$MNTPOINT/root"

      echo "Restoring blank subvolume"
      btrfs subvolume snapshot "$MNTPOINT/root-blank" "$MNTPOINT/root"
    )
  '';
  phase1Systemd = config.boot.initrd.systemd.enable;
in
{
  boot.initrd = {
    supportedFilesystems = [ "btrfs" "ext4" "swap" ];
    secrets = {
      "/crypto_keyfile.bin" = null;
    };
    postDeviceCommands = lib.mkIf (!phase1Systemd) (lib.mkBefore wipeScript);
    systemd.services.restore-root = lib.mkIf phase1Systemd {
      description = "Rollback btrfs rootfs";
      wantedBy = [ "initrd.target" ];
      requires = [
        "dev-disk-by\\x2dlabel-${hostname}.device"
      ];
      after = [
        "dev-disk-by\\x2dlabel-${hostname}.device"
        "systemd-cryptsetup@${hostname}.service"
      ];
      before = [ "sysroot.mount" ];
      unitConfig.DefaultDependencies = "no";
      serviceConfig.Type = "oneshot";
      script = wipeScript;
    };
  };

  fileSystems = {
    "/" = {
#      device = "/dev/disk/by-label/${hostname}";
       device = "/dev/disk/by-uuid/c45ddb47-4749-4133-91b9-6b8b336e75b8";
#      fsType = "btrfs";
      fsType = "ext4";
      options = [ "subvol=root" "compress=zstd" ];
    };

#    "/nix" = {
#      device = "/dev/disk/by-label/${hostname}";
#      fsType = "btrfs";
#      options = [ "subvol=nix" "noatime" "compress=zstd" ];
#    };

    #"/persist" = {
    #  device = "/dev/disk/by-label/${hostname}";
    #  fsType = "btrfs";
    #  options = [ "subvol=persist" "compress=zstd" ];
    #  neededForBoot = true;
    #};

#    "/swap" = {
#      device = "/dev/disk/by-label/${hostname}";
#      device = "/dev/disk/by-uuid/9532f291-2f58-4b0b-bf14-56f4bec5f51c";
#      fsType = "btrfs";
#       fsType = "swap";
#      options = [ "subvol=swap" "noatime" ];
#    };
  };

}
