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

let
  cfg = config.services.garage;
in

# don't mount if local VM
lib.mkIf (!config.virtualisation.isVmVariant)

{

  # gunktrunk

  sops.secrets."garage/env".owner = "garage";
  sops.secrets."garage/env".restartUnits = [ "garage.service" ];

  services.garage = {
    enable = true;
    package = pkgs.garage_0_8;

    environmentFile = config.sops.secrets."garage/env".path; # TODO: 23.11

    settings = {
      # https://search.nixos.org/options?query=services.garage.settings
      replication_mode = "1";
      #metadata_dir = ;
      data_dir = "/mnt/meconium/garage/gunktrunk";
      #data_dir = [
      #  { path = "/mnt/meconium/garage/gunktrunk"; capacity = "2T"; }
      #];

      # https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/

      db_engine = "lmdb"; # default since v0.9
      compression_level = 0; # zstd, 0 lets garage choose (curently 3)

      rpc_bind_addr = "[::]:3901";

      # Standard S3 api endpoint
      s3_api = {
        s3_region = "stoolus";
        api_bind_addr = "[::]:3900";
        root_domain = "s3.gunktrunk.kuklef.se";
      };

      # Static file serve endpoint
      s3_web = {
        bind_addr = "[::]:3902";
        root_domain = "web.gunktrunk.kuklef.se";
      };
    };
  };

  services.nginx.virtualHosts.${cfg.settings.s3_api.root_domain} = lib.mkIf cfg.enable {
    forceSSL = true;
    enableACME = true;
    locations."/" = {
      proxyPass = "http://${cfg.settings.s3_api.api_bind_addr}";
      proxyWebsockets = true;
    };
  };

  services.nginx.virtualHosts.${cfg.settings.s3_web.root_domain} = lib.mkIf cfg.enable {
    forceSSL = true;
    enableACME = true;
    locations."/" = {
      proxyPass = "http://${cfg.settings.s3_web.bind_addr}";
      proxyWebsockets = true;
    };
  };

  systemd.services = lib.mkIf cfg.enable {
    garage.serviceConfig.DynamicUser = false;
    #garage.serviceConfig.EnvironmentFile = config.sops.secrets."garage/env".path; # TODO: remove after 23.11
  };

  users = lib.mkIf cfg.enable {
    users.garage.isSystemUser = true;
    users.garage.uid = 5000;
    users.garage.group = "garage";
    groups.garage.gid = 5000;
  };

}
