# Web services configuration
{ config, pkgs, lib, ... }: {

  environment.systemPackages = with pkgs; [ libressl ];

  services.nginx = {
    enable = true;
    recommendedTlsSettings = true;
    recommendedGzipSettings = true;
    recommendedProxySettings = true;
    recommendedOptimisation = true;
    clientMaxBodySize = "0";
    sslCiphers =
      "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK:!AES128";
    sslProtocols = "TLSv1.2 TLSv1.3";
    sslDhparam = "/var/lib/dhparams/nginx.pem";
    commonHttpConfig = ''
      # Add HSTS header with preloading to HTTPS requests.
      # Adding this header to HTTP requests is discouraged
      map $scheme $hsts_header {
          https   "max-age=31536000; includeSubdomains; preload";
      }
      add_header Strict-Transport-Security $hsts_header;

      # Enable CSP for your services.
      #add_header Content-Security-Policy "script-src 'self'; object-src 'none'; base-uri 'none';" always;

      # Minimize information leaked to other domains
      add_header 'Referrer-Policy' 'origin-when-cross-origin';

      # Disable embedding as a frame
      add_header X-Frame-Options DENY;

      # Prevent injection of code in other mime types (XSS Attacks)
      add_header X-Content-Type-Options nosniff;

      # Enable XSS protection of the browser.
      # May be unnecessary when CSP is configured properly (see above)
      add_header X-XSS-Protection "1; mode=block";

      # This might create errors
      proxy_cookie_path / "/; secure; HttpOnly; SameSite=strict";
    '';
    virtualHosts = {
      "coolneng.duckdns.org" = {
        enableACME = true;
        forceSSL = true;
        locations."/radicale/" = {
          return = "301 https://radicale.coolneng.duckdns.org";
        };
        locations."/syncthing/" = {
          return = "301 https://sync.coolneng.duckdns.org";
        };
        locations."/gitea/" = {
          extraConfig =
            "rewrite ^/gitea/(.*)$ https://git.coolneng.duckdns.org/$1 last;";
        };
        locations."/miniflux/" = {
          extraConfig =
            "rewrite ^/miniflux/(.*)$ https://rss.coolneng.duckdns.org/$1 last;";
        };
      };
      "radicale.coolneng.duckdns.org" = {
        enableACME = true;
        forceSSL = true;
        locations."/" = {
          proxyPass = "http://localhost:5232/";
          extraConfig = ''
            proxy_set_header     X-Script-Name /;
            proxy_pass_header Authorization;
          '';
        };
      };
      "sync.coolneng.duckdns.org" = {
        enableACME = true;
        forceSSL = true;
        locations."/" = { proxyPass = "http://localhost:8384/"; };
      };
      "git.coolneng.duckdns.org" = {
        enableACME = true;
        forceSSL = true;
        locations."/" = { proxyPass = "http://localhost:3000/"; };
      };
      "rss.coolneng.duckdns.org" = {
        enableACME = true;
        forceSSL = true;
        locations."/" = { proxyPass = "http://localhost:8080/"; };
      };
      "shiori.coolneng.duckdns.org" = {
        enableACME = true;
        forceSSL = true;
        locations."/" = { proxyPass = "http://localhost:8181/"; };
      };
    };
  };

  # ACME certs configuration
  security.acme = {
    acceptTerms = true;
    email = "akasroua@gmail.com";
    certs = {
      "coolneng.duckdns.org" = {
        extraDomainNames = [
          "radicale.coolneng.duckdns.org"
          "sync.coolneng.duckdns.org"
          "git.coolneng.duckdns.org"
          "rss.coolneng.duckdns.org"
          "shiori.coolneng.duckdns.org"
        ];
      };
    };
  };

  # Generate dhparams
  security.dhparams = {
    enable = true;
    params = { nginx.bits = 2048; };
  };

  # PostgreSQL databases configuration
  services.postgresql = {
    enable = true;
    package = pkgs.postgresql;
    ensureDatabases = [ "gitea" "wallabag" ];
    ensureUsers = [
      {
        name = "gitea";
        ensurePermissions = { "DATABASE gitea" = "ALL PRIVILEGES"; };
      }
      {
        name = "wallabag";
        ensurePermissions = { "DATABASE wallabag" = "ALL PRIVILEGES"; };
      }
    ];
    authentication = lib.mkForce ''
      # Generated file; do not edit!
      # TYPE  DATABASE        USER            ADDRESS                 METHOD
      local   all             all                                     trust
      host    all             all             127.0.0.1/32            trust
      host    all             all             ::1/128                 trust
    '';
    identMap = ''
      gitea-users gitea gitea
    '';
  };

  # PostgreSQL daily backups
  services.postgresqlBackup = {
    enable = true;
    backupAll = true;
    location = "/vault/backups/zion/databases";
    startAt = "*-*-* 05:15:00";
  };

  # Miniflux configuration
  services.miniflux = {
    enable = true;
    adminCredentialsFile = "/var/keys/miniflux/admin";
    config = {
      BASE_URL = "https://rss.coolneng.duckdns.org";
      RUN_MIGRATIONS = "1";
    };
  };

  # Enable shiori service
  services.shiori = {
    enable = true;
    address = "localhost";
    port = 8181;
  };

  # Restart reverse proxy after services startup
  systemd.services.nginx.after = [
    "gitea.service"
    "syncthing.service"
    "miniflux.service"
    "radicale.service"
    "shiori.service"
  ];
}