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

with lib;

let cfg = config.sydnix.deertopia.bepasty;
in {
  options = {
    sydnix.deertopia.bepasty = {
      enable = mkEnableOption "Bepasty";

      port = lib.mkOption {
        default = 22018;
        type = lib.types.port;
        description = ''
          The internal port Bepasty is served on.  The actual server will be
          hosted at https://bin.deertopia.net:80/.
        '';
      };
    };
  };

  config = mkIf cfg.enable {
    sydnix.sops.secrets.bepasty-secret-key = {};
    sydnix.sops.secrets.bepasty-secret-config = {};

    sydnix.impermanence.directories = [
      config.services.bepasty.servers."bin.deertopia.net".workDir
      config.services.bepasty.servers."bin.deertopia.net".dataDir
    ];

    services.bepasty = {
      enable = true;
      servers."bin.deertopia.net" = {
        secretKeyFile = "/run/secrets/bepasty-secret-key";
        extraConfig = ''
          # HACK: The fact that this is evaluated is UB.
          $(cat /run/secrets/bepasty-secret-config)
        '';
        bind = "127.0.0.1:${builtins.toString cfg.port}";
      };
    };

    sydnix.deertopia.nginx.vhosts."bin".vhost = {
      forceSSL = true;
      enableACME = true;
      locations."/" = {
        proxyPass = "http://localhost:${builtins.toString cfg.port}";
      };
    };
  };
}
