# Edit this configuration file to define what should be installed on
# your system.  Help is available in the configuration.nix(5) man page
# and in the NixOS manual (accessible by running ‘nixos-help’).
{
  pkgs,
  lib,
  ...
}: {
  imports = [
    ./hardware-configuration-t470.nix
    ./common.nix

    ./borgbackup.nix
  ];

  networking.hostName = "t470"; # Define your hostname.

  # scanner drop point
  services.vsftpd = {
    enable = true;
    localUsers = true;
    anonymousUser = false;
    writeEnable = true;
    chrootlocalUser = true;
    userlistEnable = true;
    userlist = ["paperless-upload"];
    userlistDeny = false;
    extraConfig = ''
      log_ftp_protocol=YES
      pasv_enable=YES
      pasv_min_port=51000
      pasv_max_port=51999
      local_umask=022
      file_open_mode=0777
      user_sub_token=$USER
      local_root=/var/lib/ftp/$USER
      allow_writeable_chroot=YES
    '';
  };
  networking.firewall.allowedTCPPorts = [21];
  networking.firewall.allowedTCPPortRanges = [
    {
      from = 51000;
      to = 51999;
    }
  ];
  users.groups.paperless-upload = {};
  users.users.paperless-upload = {
    isNormalUser = true;
    group = "paperless-upload";
  };
  system.activationScripts.makeFtpDirectory = lib.stringAfter ["var"] ''
    mkdir -m 775 -p /var/lib/ftp
    chown root:root /var/lib/ftp
    mkdir -m 700 -p /var/lib/ftp/paperless-upload
    chown paperless-upload:paperless-upload /var/lib/ftp/paperless-upload
  '';
  systemd.services.uploadPaperlessDocuments = {
    path = [pkgs.openssh pkgs.inotify-tools];
    serviceConfig = {
      User = "paperless-upload";
      StandardOutput = "journal+console";
      StandardError = "journal+console";
    };
    script = ''
      # wait for document to finish uploading
      inotifywait --event close_write --timeout 60 /var/lib/ftp/paperless-upload
      # copy documents over
      ${pkgs.rsync}/bin/rsync --verbose --stats --sparse --recursive --checksum --remove-source-files /var/lib/ftp/paperless-upload/ paperless-upload@005540.xyz:/var/lib/paperless-upload
    '';
  };
  systemd.paths.uploadPaperlessDocuments = {
    pathConfig = {
      PathChanged = "/var/lib/ftp/paperless-upload/";
    };
    wantedBy = ["multi-user.target"];
  };

  # fingerprint sensor setup
  services."06cb-009a-fingerprint-sensor" = {
    enable = true;
    backend = "python-validity";
  };
}
