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

let
  secrets = import ./secrets.nix;

  branding = ''
    cp app/javascript/images/logo.svg app/javascript/images/app-icon.svg

    PATH=$PATH:${pkgs.librsvg}/bin:${pkgs.imagemagick}/bin \
      RAILS_ENV=development rake branding:generate
  '';

  mastodon-lor-sh = (pkgs.mastodon.overrideAttrs(x: {
    patchPhase = branding;
    mastodon-modules = pkgs.mastodon.mastodon-modules.overrideAttrs(y: {
      patchPhase = branding;
    });
  })).override {
    srcOverride = pkgs.applyPatches {
      src = pkgs.fetchgit {
        url = "https://github.com/mastodon/mastodon.git";
        rev = "v4.0.2"; # "v${pkgs.mastodon.version}";
        sha256 = "sha256-gNP/YDioLquxasVpgmCqLnCQx4r/gnIQ3N4YrVcI6+s=";
      };
      patches =  [
        ./patches/logo.patch
        ./patches/logo-symbol-wordmark.patch
        ./patches/mascot.patch

        ./patches/add-tango-theme.patch
        ./patches/add-merveilles-theme.patch
        ./patches/add-black-theme.patch
        ./patches/themes-config.patch
        ./patches/fix-mastodon-light-highlight-color.patch

        ./patches/fix-character-limit.patch
        ./patches/max-toot-chars-api.patch

        ./patches/simple-form.patch
      ];
    };
  };

  sidekiq-manager = pkgs.writers.writePython3 "sidekiq-manager" {} ''
    from itertools import permutations
    from subprocess import Popen


    def sidekiq(queues, connections=16):
        mastodon = "${mastodon-lor-sh}"
        cmd = [f"{mastodon}/bin/sidekiq", "-r", mastodon]
        cmd += ["-c", f"{connections}"]
        for q in queues:
            cmd += ['-q', q]
        return Popen(cmd)


    procs = [sidekiq(['mailers', 'pull', 'scheduler'])]

    queues = ['default', 'push', 'ingress']
    procs += [sidekiq(qs) for qs in permutations(queues)]

    for p in procs:
        p.wait()
  '';
in {
  services.postgresqlBackup = {
    enable = true;
    databases = [ "mastodon" ];
  };

  # Until merge of https://github.com/NixOS/nixpkgs/pull/202408
  systemd.services.mastodon-sidekiq.serviceConfig.ExecStart =
    lib.mkForce "${sidekiq-manager}";

  # https://github.com/mperham/sidekiq/wiki/Memory#bloat
  systemd.services.mastodon-sidekiq.environment.MALLOC_ARENA_MAX = "2";

  services.mastodon = {
    enable = true;

    package = mastodon-lor-sh;

    localDomain = "lor.sh";
    configureNginx = true;

    smtp = {
      createLocally = false;
      authenticate = true;
      host = "smtp.eu.mailgun.org";
      port = 587;
      fromAddress = "Mastodon <mastodon@m.lor.sh>";
      user = "mastodon@m.lor.sh";
      passwordFile = builtins.toFile "smtp-password" secrets.smtpPassword;
    };

    vapidPublicKeyFile = builtins.toFile "vapidPublicKey" secrets.vapidPublicKey;
    secretKeyBaseFile = builtins.toFile "secretKeyBase" secrets.secretKeyBase;
    otpSecretFile = builtins.toFile "otpSecret" secrets.otpSecret;
    vapidPrivateKeyFile = builtins.toFile "vapidPrivateKey" secrets.vapidPrivateKey;

    extraConfig = {
      S3_ENABLED = "true";
      S3_PROTOCOL = "https";
      S3_BUCKET = "lor-sh";
      S3_REGION = "eu-central-1";
      S3_HOSTNAME = "s3.eu-central-1.wasabisys.com";
      S3_ENDPOINT = "https://s3.eu-central-1.wasabisys.com/lor-sh";
      S3_ALIAS_HOST = "s3.eu-central-1.wasabisys.com/lor-sh/lor-sh";
      AWS_ACCESS_KEY_ID = secrets.AWS_ACCESS_KEY_ID;
      AWS_SECRET_ACCESS_KEY = secrets.AWS_SECRET_ACCESS_KEY;

      DEEPL_API_KEY = secrets.DEEPL_API_KEY;
      DEEPL_PLAN = "pro";
    };
  };
}