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

let cfg = config.sydnix.deertopia.anki-sync-server;
in {
  options.sydnix.deertopia.anki-sync-server = {
    enable = lib.mkEnableOption "Anki";
  };

  config = lib.mkIf cfg.enable {
    sydnix.impermanence.directories = [
      "/var/lib/private/anki-sync-server"
    ];

    sydnix.sops.secrets.anki-password.mode = "0600";

    sydnix.deertopia.nginx.vhosts."anki" = {
      directory = null;
      vhost = {
        forceSSL = true;
        enableACME = true;
        locations."/".extraConfig =
          let port = builtins.toString config.services.anki-sync-server.port;
          in ''
            proxy_pass http://127.0.0.1:${port}/;
          '';
      };
    };

    services.anki-sync-server = {
      enable = true;
      address = "0.0.0.0";
      openFirewall = true;
      users = [
        {
          username = "msyds";
          passwordFile = config.sops.secrets.anki-password.path;
        }
      ];
    };
  };
}
