{ pkgs, config, ... }:
let
  myKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIArRfRumAbMcRypGundddfVg7t+VOwVeQ+HUQfI9AFbX flygrounder@home";
  stalwartCaddyCertsDir = "/var/lib/caddy/.local/share/caddy/certificates/acme-v02.api.letsencrypt.org-directory/mail.flygrounder.ru";
  stalwartCertsDir = "/var/lib/stalwart-mail/certs";
in
{
  age.secrets = {
    stalwart-admin-password = {
      file = ../../secrets/stalwart-admin-password.age;
      owner = "stalwart-mail";
    };
    restic-environment = {
      file = ../../secrets/restic-environment.age;
      owner = "root";
    };
    restic-password = {
      file = ../../secrets/restic-password.age;
      owner = "root";
    };
  };

  users.users = {
    flygrounder = {
      openssh.authorizedKeys.keys = [
        myKey
      ];
    };
    root = {
      openssh.authorizedKeys.keys = [
        myKey
      ];
    };
  };

  environment.systemPackages = with pkgs; [ restic ];

  home-manager.users.flygrounder.custom = {
    catppuccin.enable = true;
    cli.enable = true;
    neovim.enable = true;
  };

  services = {
    caddy = {
      enable = true;
      virtualHosts = {
        "flygrounder.ru" = {
          extraConfig = ''
            reverse_proxy localhost:1234
          '';
        };
        "mtg-bot.flygrounder.ru" = {
          extraConfig = ''
            reverse_proxy localhost:3000
          '';
        };
        "syncthing.flygrounder.ru" = {
          extraConfig = ''
            reverse_proxy localhost:8384 {
              header_up Host localhost
            }
          '';
        };
        "vaultwarden.flygrounder.ru" = {
          extraConfig = ''
            encode zstd gzip

            reverse_proxy localhost:8222 {
              header_up X-Real-IP {remote_host}
            }
          '';
        };
        "mail.flygrounder.ru" = {
          extraConfig = ''
            reverse_proxy localhost:8080
          '';
        };
      };
    };
    stalwart = {
      enable = true;
      openFirewall = true;
      settings = {
        server = {
          hostname = "mail.flygrounder.ru";
          tls = {
            enable = true;
            implicit = true;
          };
          listener = {
            smtp = {
              protocol = "smtp";
              bind = "0.0.0.0:25";
            };
            submissions = {
              bind = "0.0.0.0:465";
              protocol = "smtp";
              tls.implicit = true;
            };
            imaps = {
              bind = "0.0.0.0:993";
              protocol = "imap";
              tls.implicit = true;
            };
            jmap = {
              bind = "127.0.0.1:8080";
              protocol = "http";
            };
          };
        };
        certificate."default" = {
          cert = "%{file:/var/lib/stalwart-mail/certs/mail.flygrounder.ru.crt}%";
          private-key = "%{file:/var/lib/stalwart-mail/certs/mail.flygrounder.ru.key}%";
        };

        authentication.fallback-admin = {
          user = "admin";
          secret = "%{file:/run/agenix/stalwart-admin-password}%";
        };
        tracer."log" = {
          type = "log";
          path = "/var/log/stalwart-mail";
        };
      };
    };
    openssh = {
      enable = true;
      settings = {
        PasswordAuthentication = false;
      };
    };
    vaultwarden = {
      enable = true;
      config = {
        DOMAIN = "https://vaultwarden.flygrounder.ru";
        SIGNUPS_ALLOWED = false;

        ROCKET_ADDRESS = "127.0.0.1";
        ROCKET_PORT = 8222;
        ROCKET_LOG = "critical";
      };
    };
  };

  systemd = {
    paths.stalwart-certs = {
      wantedBy = [ "multi-user.target" ];
      pathConfig = {
        PathModified = "${stalwartCaddyCertsDir}/mail.flygrounder.ru.crt";
      };
    };
    services.stalwart-certs = {
      serviceConfig = {
        Type = "oneshot";
      };
      script = ''
        mkdir -p ${stalwartCertsDir}
        cp -L ${stalwartCaddyCertsDir}/*.{key,crt} ${stalwartCertsDir}/
        chown stalwart-mail:stalwart-mail ${stalwartCertsDir}/*
        chmod 600 ${stalwartCertsDir}/*
        systemctl restart stalwart
      '';
    };
  };

  imports = [
    ./hardware-configuration.nix
    ./disko-config.nix
  ];

  nix.settings.trusted-users = [ "flygrounder" ];

  networking = {
    firewall = {
      allowedTCPPorts = [
        80
        443
        25
        465
        993
      ];
    };
    nameservers = [
      "1.1.1.1"
      "8.8.8.8"
    ];
    interfaces.ens3.ipv4.addresses = [
      {
        address = "62.109.27.62";
        prefixLength = 32;
      }
    ];
    defaultGateway = {
      address = "10.0.0.1";
      interface = "ens3";
    };
  };

  services.restic.backups =
    let
      mkBackup =
        { service, path }:
        {
          paths = [
            path
          ];
          repository = "s3:https://s3.firstvds.ru/flygrounder-backups/${service}";
          initialize = true;
          timerConfig = {
            OnCalendar = "03:00";
            Persistent = true;
            RandomizedDelaySec = "10m";
          };
          environmentFile = "/run/agenix/restic-environment";
          passwordFile = "/run/agenix/restic-password";
          backupPrepareCommand = "systemctl stop ${service}";
          backupCleanupCommand = "systemctl start ${service}";
          pruneOpts = [
            "--keep-daily 14"
            "--keep-weekly 4"
            "--keep-monthly 2"
          ];
        };
    in
    {
      stalwart = mkBackup {
        service = "stalwart";
        path = config.services.stalwart.dataDir;
      };
      vaultwarden = mkBackup {
        service = "vaultwarden";
        path = "/var/lib/vaultwarden";
      };
    };
}
