{ pkgs, ... }:
let
  masSettings = {
    http = {
      listeners = [
        {
          name = "web";
          resources = [
            { name = "discovery"; }
            { name = "human"; }
            { name = "oauth"; }
            { name = "compat"; }
            { name = "graphql"; }
            { 
              name = "assets";
              path = "${pkgs.matrix-authentication-service}/share/matrix-authentication-service/assets/";
            }
          ];
          binds = [{
            host = "localhost";
            port = 8080;
          }];
          proxy_protocol = false;
        }
        {
          name = "internal";
          resources = [{
            name = "health";
          }];
          binds = [{
            host = "localhost";
            port = 8081;
          }];
          proxy_protocol = false;
        }
      ];
      trusted_proxies = [
        "192.168.0.0/16"
        "172.16.0.0/12"
        "10.0.0.0/10"
        "127.0.0.1/8"
        "fd00::/8"
        "::1/128"
      ];
      public_base = "https://mas.nekover.se";
    };
    database = {
      uri = "postgresql://mas_user:mas@localhost/mas";
      max_connections = 10;
      min_connections = 0;
      connect_timeout = 30;
      idle_timeout = 600;
      max_lifetime = 1800;
    };
    passwords = {
      enabled = true;
      schemes = [
        {
          version = 1;
          algorithm = "bcrypt";
        }
        {
          version = 2;
          algorithm = "argon2id";
        }
      ]; 
      minimum_complexity = 8;
    };
  };
  masSettingsFile = ((pkgs.formats.yaml { }).generate "mas-config" masSettings);
in
{
  environment.systemPackages = with pkgs; [
    matrix-authentication-service
    syn2mas
  ];


  systemd.services.matrix-authentication-service = {
    description = "Matrix Authentication Service";
    after = [ "network-online.target" "postgresql.service" ];
    requires = [ "postgresql.service" ];
    wants = [ "network-online.target" ];

    serviceConfig = {
      Type = "simple";
      ExecStart = "${pkgs.matrix-authentication-service}/bin/mas-cli server --config=${masSettingsFile} --config=/secrets/matrix-mas-secret-config.secret";
      WorkingDirectory = "${pkgs.matrix-authentication-service}";
      User = "matrix-synapse";
      Group = "matrix-synapse";
    };

    wantedBy = [
      "multi-user.target"
    ];
  };
}