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

  environment.etc."gitconfig".text = ''
    [safe]
    	directory = *
  '';

  networking.firewall.allowedTCPPorts = [ 2049 8333 ];

  security.acme = {
    acceptTerms = true;
    certs."arrakis.bitgnome.net".postRun = ''
      ${pkgs.acl}/bin/setfacl -m u:postfix:--x /var/lib/acme/arrakis.bitgnome.net
      ${pkgs.acl}/bin/setfacl -m u:postfix:r-- /var/lib/acme/arrakis.bitgnome.net/{fullchain,key}.pem
      ${pkgs.systemd}/bin/systemctl reload postfix.service
    '';
    defaults.email = "nipsy@bitgnome.net";
  };

  services = {

    cgit = {
      "arrakis.bitgnome.net" = {
        enable = true;
        gitHttpBackend.checkExportOkFiles = false;
        nginx.location = "/nipsy/git/";
        scanPath = "/home/nipsy/www/git";
        settings = {
          about-filter = "${pkgs.cgit}/lib/cgit/filters/about-formatting.sh";
          branch-sort = "age";
          clone-url = "https://$HTTP_HOST$SCRIPT_NAME/$CGIT_REPO_URL";
          css = "/nipsy/git/cgit.css";
          enable-commit-graph = true;
          enable-follow-links = true;
          enable-git-config = true;
          enable-index-links = true;
          enable-log-filecount = true;
          enable-log-linecount = true;
          logo = "/nipsy/git/cgit.png";
          max-stats = "quarter";
          mimetype-file = "${pkgs.mailcap}/etc/mime.types";
          readme = ":README.md";
          remove-suffix = 1;
          root-desc= "Dune.  Desert planet.";
          root-title = "Spice Factory";
          snapshots = "all";
          source-filter = "${pkgs.cgit}/lib/cgit/filters/syntax-highlighting.py";
        };
      };
    };

    clamav.updater.enable = true;

    cron.enable = true;

    dictd.enable = true;

    iperf3.openFirewall = true;

    jellyfin = {
      enable = true;
      #package = pkgs.master.jellyfin;
    };

    minidlna = {
      enable = true;
      openFirewall = true;
      settings = {
        inotify = "yes";
        media_dir = [
          "A,/data/home/nipsy/www/media/music"
        ];
      };
    };

    nfs = {
      server = {
        enable = true;
        exports = ''
          /srv/caladan/downloads	192.168.1.4/32(rw,root_squash,fsid=1)
          /srv/caladan/www	192.168.1.4/32(rw,root_squash,fsid=2)
          /srv/nfs/keepers	192.168.1.0/24(ro,all_squash,insecure,fsid=3)
          /srv/nfs/movies	192.168.1.0/24(ro,all_squash,insecure,fsid=4)
          /srv/nfs/tv	192.168.1.0/24(ro,all_squash,insecure,fsid=5)
        '';
      };
      settings = {
        nfsd = {
          udp = false;
          vers2 = false;
          vers3 = false;
          vers4 = true;
        };
      };
    };

    nginx = let

      sys = lib.nixosSystem {
        modules = [
          ({ config, pkgs, lib, modulesPath, ... }: {
            imports = [
              (modulesPath + "/installer/netboot/netboot-minimal.nix")
              ../common/optional/services/nolid.nix
            ];

            config = {
              environment.systemPackages = [
                pkgs.git
                pkgs.iperf
                pkgs.rsync
              ];

              nix.settings.experimental-features = [ "nix-command" "flakes" ];

              services.openssh = {
                enable = true;
                openFirewall = true;

                settings = {
                  KbdInteractiveAuthentication = false;
                  PasswordAuthentication = false;
                };
              };

              users.users = {
                nixos.openssh.authorizedKeys.keys = [ (builtins.readFile ../common/users/nipsy/keys/id_arrakis.pub) ];
                root.openssh.authorizedKeys.keys = [ (builtins.readFile ../common/users/nipsy/keys/id_arrakis.pub) ];
              };
            };
          })
          { nixpkgs.hostPlatform = "x86_64-linux"; }
        ];
      };

      build = sys.config.system.build;

    in {
      appendHttpConfig = ''
        geo $geo {
        	default 0;
        	127.0.0.1 1;
        	::1 1;
        	192.168.1.0/24 1;
        }

        map $scheme $req_ssl {
        	default 1;
        	http 0 ;
        }

        map "$geo$req_ssl" $force_enable_ssl {
        	default 0;
        	00 1;
        }
      '';
      enable = true;

      # Use recommended settings
      recommendedGzipSettings = true;
      recommendedOptimisation = true;
      #recommendedProxySettings = true;
      recommendedTlsSettings = true;

      # Only allow PFS-enabled ciphers with AES256
      sslCiphers = "AES256+EECDH:AES256+EDH:!aNULL";

      virtualHosts = {
        "arrakis.bitgnome.net" = {
          addSSL = true;
          enableACME = true;

          extraConfig = ''
            if ($force_enable_ssl) {
            	return 301 https://$host$request_uri;
            }
          '';

          locations = {
            "= /boot/bzImage" = {
              alias = "${build.kernel}/bzImage";
            };

            "= /boot/initrd" = {
              alias = "${build.netbootRamdisk}/initrd";
            };

            "= /boot/netboot.ipxe" = {
              alias = "${build.netbootIpxeScript}/netboot.ipxe";
            };

            "/" = {
              tryFiles = "$uri $uri/ =404";
            };

            "/jellyfin" = {
              return = "302 $scheme://$host/jellyfin/";
            };

            "/jellyfin/" = {
              extraConfig = ''
                proxy_pass_request_headers on;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header X-Forwarded-Host $http_host;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection $http_connection;
                proxy_buffering off;

                # CORS setup
                add_header 'Access-Control-Allow-Origin' '*' always;
                add_header 'Access-Control-Expose-Headers' 'Content-Length';

                # Allow CORS preflight requests
                if ($request_method = 'OPTIONS') {
                	add_header 'Access-Control-Allow-Origin' '*';
                	add_header 'Access-Control-Max-Age' 1728000;
                	add_header 'Content-Type' 'text/plain charset=UTF-8';
                	add_header 'Content-Length' 0;
                	return 204;
                }
              '';
              proxyPass = "http://192.168.1.2:8096/jellyfin/";

            };

            "/nipsy" = {
              tryFiles = "$uri $uri/ =404";
            };

            "/nipsy/iso" = {
              extraConfig = ''
                autoindex on;
              '';
            };

            "/nipsy/media/emu/mame" = {
              basicAuthFile = "${config.sops.secrets.htpasswd.path}";
              extraConfig = ''
                autoindex on;
              '';
            };

            "/nipsy/media/misc" = {
              extraConfig = ''
                autoindex on;
              '';
            };
          };

          root = "/var/www";
        };
      };
    };

    openssh.settings = {
      StreamLocalBindUnlink = true;
    };

    postfix = let my_email = "nipsy@bitgnome.net"; in {
      enable = true;
      extraAliases = ''
        nipsy: ${my_email}
      '';
      rootAlias = my_email;
      settings.main = {
        myhostname = "arrakis.bitgnome.net";
        relayhost = [
          "[mail.bitgnome.net]:587"
        ];
        smtpd_tls_chain_files = [
          "/var/lib/acme/arrakis.bitgnome.net/key.pem"
          "/var/lib/acme/arrakis.bitgnome.net/fullchain.pem"
        ];
      };
    };

    printing.enable = true;

    sabnzbd = {
      enable = true;
      user = "nipsy";
      group = "nipsy";
      configFile = "/home/nipsy/.sabnzbd/sabnzbd.ini";
    };

    samba = {
      enable = true;
      settings = {
        global = {
          "invalid users" = [
            "root"
          ];
          "passwd program" = "/run/wrappers/bin/passwd %u";
          security = "user";
          "smb1 unix extensions" = "no";
        };
        homes = {
          browseable = "no";
          "create mask" = "0775";
          "directory mask" = "0775";
          "read only" = "no";
          "valid users" = "%S";
          "wide links" = "yes";
        };
        nipsy-ro = {
          browseable = "no";
          path = "/home/nipsy";
          "read only" = "yes";
          "valid users" = "nipsy";
          "wide links" = "yes";
        };
      };
    };

    smartd = let my_email_addr = "nipsy@bitgnome.net"; in {
      enable = true;
      devices = [
        {
          device = "/dev/disk/by-id/nvme-WD_BLACK_SN850X_4000GB_23162P800005";
          options = "-a -o on -S on -m ${my_email_addr}";
        }
        {
          device = "/dev/disk/by-id/nvme-WD_BLACK_SN850X_4000GB_23162P800014";
          options = "-a -o on -S on -m ${my_email_addr}";
        }
        {
          device = "/dev/disk/by-id/ata-WDC_WUH722020ALE604_2LG5X74K";
          options = "-a -o on -S on -s (S/../.././02|L/../../5/03) -m ${my_email_addr}";
        }
        {
          device = "/dev/disk/by-id/ata-WDC_WUH722020ALE604_2LGHJAUF";
          options = "-a -o on -S on -s (S/../.././02|L/../../5/03) -m ${my_email_addr}";
        }
        {
          device = "/dev/disk/by-id/ata-WDC_WUH722020ALE604_2LG26NHF";
          options = "-a -o on -S on -s (S/../.././02|L/../../5/03) -m ${my_email_addr}";
        }
        {
          device = "/dev/disk/by-id/ata-WDC_WUH722020BLE6L4_8LKLLAAE";
          options = "-a -o on -S on -s (S/../.././02|L/../../5/03) -m ${my_email_addr}";
        }
        {
          device = "/dev/disk/by-id/ata-WDC_WUH722020BLE6L4_8LK84H9V";
          options = "-a -o on -S on -s (S/../.././02|L/../../5/03) -m ${my_email_addr}";
        }
        {
          device = "/dev/disk/by-id/ata-WDC_WUH722020BLE6L4_2LGKG71F";
          options = "-a -o on -S on -s (S/../.././02|L/../../5/03) -m ${my_email_addr}";
        }
        {
          device = "/dev/disk/by-id/ata-WDC_WUH722020BLE6L4_9AG00UKJ";
          options = "-a -o on -S on -s (S/../.././02|L/../../5/03) -m ${my_email_addr}";
        }
        {
          device = "/dev/disk/by-id/ata-WDC_WUH722020BLE6L4_8LG806ZA";
          options = "-a -o on -S on -s (S/../.././02|L/../../5/03) -m ${my_email_addr}";
        }
      ];
    };

    udev.packages = [
      pkgs.vial
    ];

    #xserver.videoDrivers = [ "nvidia" ];

  };

  #systemd.services.nginx.serviceConfig.ProtectHome = lib.mkForce false;

}
