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

with lib;

let cfg = config.services.bin;
in {
  options = {
    services.bin = {
      enable = mkEnableOption "Pastebin";

      address = mkOption {
        type = types.nullOr types.str;
        default = "127.0.0.1";
        description = "Address on which the webserver runs";
      };

      binaryUploadLimit = mkOption {
        type = types.nullOr types.int;
        default = 100;
        description = "Binary uploads file size limit (in MiB)";
      };

      textUploadLimit = mkOption {
        type = types.nullOr types.int;
        default = 16;
        description = "Text uploads file size limit (in MiB)";
      };

      clientDesc = mkOption {
        type = types.nullOr types.bool;
        default = false;
        description = "Include client description [env: CLIENT_DESC=]";
      };

      port = mkOption {
        type = types.nullOr types.int;
        default = 6162;
        description = "Port on which the webserver runs";
      };

      upload = mkOption {
        type = types.nullOr types.str;
        default = "./upload";
        description = "Path to the uploads folder";
      };
    };
  };

  config = mkIf cfg.enable {
    systemd.services.bin = {
      wantedBy = [ "multi-user.target" ];
      description = "Starts pastebin service.";
      after = [ "network.target" ];

      serviceConfig = {
        Type = "simple";
        Environment =
          ''BIN_LIMITS={form="${toString cfg.textUploadLimit} MiB"}'';
        ExecStart = "${pkgs.bin}/bin/bin -a ${toString cfg.address} -b ${
            toString cfg.binaryUploadLimit
          } -p ${toString cfg.port} -u ${toString cfg.upload}";
        WorkingDirectory = "/var/lib/bin_rs";
        Restart = "always";
      };
    };
  };
}
