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

with lib;

let
  cfg = config.services.scan-to-gpg;
in {

  options = {
    services.scan-to-gpg = {
      enable = mkEnableOption "scan-to-gpg";
      host = mkOption {
        type = types.str;
        default = "0.0.0.0";
        description = "Interface to bind FTP server to";
      };
      port = mkOption {
        type = with types; nullOr port;
        default = null;
        description = "Port for FTP server";
      };
      user = mkOption {
        type = with types; nullOr str;
        default = null;
        description = "Username for FTP login";
      };
      passFile = mkOption {
        type = with types; nullOr path;
        default = null;
        description = "Path to file containing password for FTP login";
      };
      output = mkOption {
        type = types.path;
        default = "/var/lib/scan-to-gpg";
        description = "Path to directory where encrypted files are stored in";
      };
      gpgkey = mkOption {
        type = types.path;
        description = "Path to a file containing to GPG public key to encrypt to";
      };
    };
  };

  config = mkIf cfg.enable {

    systemd.services.scan-to-gpg = {
      description = "FTP server that saves uploaded files GPG encrypted";
      wantedBy = [ "multi-user.target" ];
      requires = [ "network.target" ];
      after = [ "network.target" ];

      serviceConfig = {
        Type = "simple";
        User = "scan-to-gpg";
        Group = "scan-to-gpg";
        StateDirectory = "scan-to-gpg";
        StateDirectoryMode = "775";
        LoadCredential = mkIf (cfg.passFile != null) "pass-file:${cfg.passFile}";
      };

      environment = mkIf (cfg.passFile != null) {
        PASS_FILE = "%d/pass-file";
      };

      script = ''
        ${getExe pkgs.scan-to-gpg} -host ${cfg.host} ${
          optionalString (cfg.port != null) "-port ${toString cfg.port} "
        }${
          optionalString (cfg.user != null) "-user ${cfg.user} "
        }${
          optionalString (cfg.passFile != null) "-pass \"\$(cat \"\${PASS_FILE}\")\" "
        }-output ${cfg.output} -gpgkey ${cfg.gpgkey}
      '';

    };

    users.users.scan-to-gpg = {
      isSystemUser = true;
      group = "scan-to-gpg";
    };

    users.groups.scan-to-gpg = {};

  };
}