{ pkgs, lib, config, ... }:
let
  inherit (config.services) sourcehut;
  inherit (config.users) groups;
  domain = "sourcephile.wg";
in
{
#boot.isContainer = true;
#networking.firewall.allowedTCPPorts = [ 80 ];
networking.hosts = {
  "192.168.42.2" = [domain] ++ map (d: "${d}.${domain}") sourcehut.services;
};
services.sourcehut = {
  enable = true;
  originBase = "${domain}";
  address = domain;
  services = [
    #"builds"
    "git"
    #"hub"
    #"man"
    "meta"
  ];
  /*
  builds = {
    enableWorker = true;
  };
  */
  git = {
  };
  meta = {
    port = 5000;
  };
  settings = {
    "sr.ht" = {
      environment = "production";
      global-domain = "${domain}";
      origin = "http://${domain}";
      # nix shell nixpkgs#sourcehut.coresrht -c srht-keygen network
      network-key = "OeXzQ6A8Vcgt5QJkXScuxeXCtfdKzKev99BRNb3_CWQ=";
      # nix shell nixpkgs#sourcehut.coresrht -c srht-keygen service
      service-key = "62427596fed00fa48c19f95bc85c14d0c618a5f8c130b53ba9a6a6b403bf1507";
    };
    # nix shell nixpkgs#sourcehut.metasrht -c metasrht-manageuser -t admin -e mymail@gmail.com misuzu
    "meta.sr.ht" = {
      origin = "http://meta.${domain}";
      api-origin = "http://meta.${domain}:5100";
    };
    "meta.sr.ht::settings" = {
      onboarding-redirect = "http://meta.${domain}";
      registration = "yes";
    };
    # nix shell nixpkgs#sourcehut.coresrht -c srht-keygen webhook
    webhooks.private-key= "U7yd/8mGs/v0O3kId4jpeSghUCa9tqP1fYQwSV8UOqo=";
    "builds.sr.ht" = {
      origin = "http://builds.${domain}";
      oauth-client-secret = "8f5fc39b5948907e62c737f6b48462dc";
      oauth-client-id = "299db9f9c2013170";
    };
  };
};
services.nginx.virtualHosts = {
  #"builds.${domain}".forceSSL = lib.mkForce false;
  "git.${domain}".forceSSL = lib.mkForce false;
  "hub.${domain}".forceSSL = lib.mkForce false;
  "logs.${domain}".forceSSL = lib.mkForce false;
  "man.${domain}".forceSSL = lib.mkForce false;
  "meta.${domain}".forceSSL = lib.mkForce false;
  "${domain}".forceSSL = lib.mkForce false;
};
users.groups."postgres".members = map (n: sourcehut.${n}.user) sourcehut.services;
systemd.services.postgresql = {
  /*
    connection_limit=64 \
    encoding=UTF8 \
    lc_collate=fr_FR.UTF-8 \
    lc_type=fr_FR.UTF-8 \
    owner="${sourcehut.git.database}" \
    pg_createdb "${sourcehut.git.database}" >/dev/null </dev/null

    pg_adduser "${sourcehut.git.database}" "${sourcehut.git.database}" >/dev/null
  */
  postStart = lib.mkAfter ''
    $PSQL -d "${sourcehut.meta.database}" -AqtX --set ON_ERROR_STOP=1 -f - <<EOF
      GRANT USAGE,CREATE ON schema public TO "${sourcehut.git.user}";
      GRANT USAGE,CREATE ON schema public TO "${sourcehut.meta.user}";
    EOF
  '';
};
}