{ config, pkgs, lib, ... }:

with pkgs;

{
  # NixOS wants to enable GRUB by default
  boot.loader.grub.enable = false;

  # A bunch of boot parameters needed for optimal runtime on RPi 4B
  boot.kernelPackages = linuxPackages_rpi4;
  boot.kernelParams = [
    "zfs.zfs_arc_max=134217728"
    "console=TTYAMA0,115200"
    "console=tty1"
    "8250.nr_uarts=1"
    "iomem=relaxed"
    "strict-devmem=0"
  ];
  boot.loader.raspberryPi = {
    enable = true;
    version = 4;
  };

  environment.systemPackages = [ libraspberrypi htop vim ];

  # Add a swap file
  swapDevices = [{
    device = "/swapfile";
    size = 4096;
  }];

  # Configure basic SSH access
  services.openssh = {
    enable = true;
    permitRootLogin = "yes";
  };

  # Cleanup tmp on startup
  boot.cleanTmpDir = true;

  # Create coolneng user
  users.users.coolneng = {
    isNormalUser = true;
    home = "/home/coolneng";
    extraGroups = [ "wheel" "docker" ];
    openssh.authorizedKeys.keys = [
      "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFRqINHR7/zc+c3/PuR+NeSsBHXXzBiEtFWSK6QaxQTW coolneng@panacea"
    ];
    shell = "${fish}/bin/fish";
  };

  # Set vim as default editor
  programs.vim.defaultEditor = true;

  # Set timezone and synchronize NTP
  time.timeZone = "Europe/Brussels";
  services.timesyncd.enable = true;

  # Enable ZFS support
  boot.supportedFilesystems = [ "zfs" ];

  # Don't import encrypted datasets
  boot.zfs.requestEncryptionCredentials = false;

  # Scrub zpool monthly
  services.zfs.autoScrub = {
    enable = true;
    interval = "monthly";
  };

  # Auto-upgrade the system and reboot if needed
  system.autoUpgrade = {
    enable = true;
    allowReboot = true;
  };

  # Run Nix garbage collector, while avoiding recompilation
  nix = {
    settings.auto-optimise-store = true;
    gc = {
      automatic = true;
      options = "--delete-older-than 14d";
    };
    extraOptions = ''
      keep-outputs = true
      keep-derivations = true
      gc-keep-outputs = true
    '';
  };

  # Configure fish shell
  programs.fish.enable = true;
  users.users.root = {
    shell = "${fish}/bin/fish";
    openssh.authorizedKeys.keys = [
      "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFRqINHR7/zc+c3/PuR+NeSsBHXXzBiEtFWSK6QaxQTW coolneng@panacea"
    ];
  };

  # Rotate logs after 7 days
  services.journald.extraConfig = "SystemMaxFiles=7";

  # Increase inotify limits
  boot.kernel.sysctl = { "fs.inotify.max_user_watches" = 204800; };

  # MOTD message
  programs.fish.interactiveShellInit = "${./scripts/motd.sh}";

  # Import other configuration modules
  imports = [
    ./modules/hardware-configuration.nix
    ./modules/networking.nix
    ./modules/datasync.nix
    ./modules/webstack.nix
    ./modules/devops.nix
    ./modules/monitoring.nix
    ./modules/periodic.nix
    ./modules/communication.nix
    ./modules/information.nix
  ];

}