{
  config,
  pkgs,
  lib,
  ...
}: let
  home-manager = builtins.fetchTarball "https://github.com/nix-community/home-manager/archive/release-25.11.tar.gz";
  cfg = config.services.forgejo;
  srv = cfg.settings.server;
  choose = paths: builtins.head (builtins.filter (p: builtins.pathExists p) paths);
  mapleZip = pkgs.fetchurl {
    url = "https://github.com/subframe7536/maple-font/releases/download/v7.9/MapleMonoNormal-NF-unhinted.zip";
    sha256 = "1j8bh8fzrnrj4348xj8l1jpbchbblhi2a7gryarf2mi88xr1yc3f";
  };

  # Add a runCommand that unpacks the downloaded zip and exposes a stable ttf path
  mapleFonts = pkgs.runCommand "maple-fonts" {buildInputs = [pkgs.unzip];} ''
    mkdir -p $out/tmp
    unzip -q ${mapleZip} -d $out/tmp
    f="$(find $out/tmp -type f -name '*.ttf' | head -n1)"
    if [ -z "$f" ]; then
      echo "no ttf found" >&2
      exit 1
    fi
    mkdir -p $out/fonts
    cp "$f" $out/fonts/MapleMonoNerd.ttf
  '';

  # Package local Jost OTF files from the repository into the Nix store so
  # they can be installed into the Forgejo custom assets directory.
  jostFonts = pkgs.runCommand "jost-fonts" {src = ../styling/forgejo/Jost/OpenType;} ''
    mkdir -p $out/fonts
    cp -a $src/*.otf $out/fonts/
  '';
in {
  options.local = {
    hostname = lib.mkOption {
      type = lib.types.str;
      default = "nixos-default";
      description = "System hostname";
    };
    username = lib.mkOption {
      type = lib.types.str;
      default = "user";
      description = "Primary user username";
    };
    userDescription = lib.mkOption {
      type = lib.types.str;
      default = "NixOS User";
      description = "Primary user description";
    };
    address = lib.mkOption {
      type = lib.types.str;
      default = "10.1.1.100";
      description = "Static IP address";
    };
  };

  imports = [
    (choose [./modules/desktop-manager/sway_greetd_homemanager.nix ../desktop-manager/sway_greetd_homemanager.nix])
    (choose [./modules/local/hostname_username.nix ../local/hostname_username.nix])
    (choose [./modules/local/networking_local.nix ../local/networking_local.nix])
    (choose [./modules/toolsets/remote_building.nix ../toolsets/remote_building.nix])
    (choose [./modules/bootloader/seabios-assigned-proxmox-at-birth.nix ../bootloader/seabios-assigned-proxmox-at-birth.nix])
    (choose [./modules/lix-default.nix ../lix-default.nix])
    (choose [./modules/toolsets/grafana_metric.nix ../toolsets/grafana_metric.nix])
  ];

  config = {
    local.hostname = "forgejoprg";
    local.username = "forgejoprg";
    local.userDescription = "Forgejo Admin";
    local.address = "10.1.1.4";

    # Enable Fedgejo service
    services.nginx = {
      enable = true;
      virtualHosts."git.prg.local" = {
        # Remove forceSSL and enableACME for local network
        # forceSSL = true;
        # enableACME = true;
        extraConfig = ''
          client_max_body_size 512M;
        '';
        locations."/".proxyPass = "http://localhost:${toString srv.HTTP_PORT}";
      };
    };

    # Enable PostgreSQL for Forgejo
    services.postgresql.enable = true;

    # Forgejo configuration
    services.forgejo = {
      enable = true;
      # Explicit custom directory where Forgejo will look for custom templates/assets
      # Ensure this matches what systemd.tmpfiles will populate below.
      customDir = "/var/lib/forgejo/custom";
      database = {
        createDatabase = false; # Database already created, DO NOT REMOVE THIS OR IT WILL DEFAULT INTO INTERNAL ONE
        type = "postgres";
        host = "10.1.1.251"; # IP of your database server
        name = "forgejo";
        user = "forgejo";
        passwordFile = "/home/forgejoprg/password.txt"; # Store password in a separate file for security
      };
      lfs.enable = true;

      settings = {
        server = {
          DOMAIN = "git.prg-radio.org";
          ROOT_URL = "https://git.prg-radio.org/";
          HTTP_PORT = 30000;
          # SSH integration
          SSH_PORT = lib.head config.services.openssh.ports;
        };

        # Temporarily allow registration to create admin user
        service.DISABLE_REGISTRATION = false;

        # Enable Actions support
        actions = {
          ENABLED = true;
          DEFAULT_ACTIONS_URL = "github";
        };

        # Optional: Email configuration
        mailer = {
          ENABLED = false;
        };
      };

      settings.ui = {
        DEFAULT_THEME = "forgejo-auto";
        THEMES = "forgejo-auto, forgejo-light, forgejo-dark";
      };
    };

    systemd.tmpfiles.rules = [
      "d '${config.services.forgejo.customDir}/templates' - forgejo forgejo - -"
      # create the custom/templates/custom folder so header.tmpl can live under templates/custom
      "d '${config.services.forgejo.customDir}/templates/custom' - forgejo forgejo - -"
      "d '${config.services.forgejo.customDir}/public' - forgejo forgejo - -"
      "d '${config.services.forgejo.customDir}/public/assets' - forgejo forgejo - -"
      # ensure fonts directory exists
      "d '${config.services.forgejo.customDir}/public/assets/fonts' - forgejo forgejo - -"
      # ensure css directory exists so we can place theme css
      "d '${config.services.forgejo.customDir}/public/assets/css' - forgejo forgejo - -"
      # ensure image directory exists for site/app logos
      "d '${config.services.forgejo.customDir}/public/assets/img' - forgejo forgejo - -"
      # install the TTF from the Nix store into the Forgejo customDir
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/MapleMonoNerd.ttf' - forgejo forgejo - ${mapleFonts}/fonts/MapleMonoNerd.ttf"
      # copy Jost OTF files from the Nix store into Forgejo's fonts dir (add one line per font present in the repo)
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-100-Hairline.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-100-Hairline.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-100-HairlineItalic.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-100-HairlineItalic.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-200-Thin.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-200-Thin.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-200-ThinItalic.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-200-ThinItalic.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-300-Light.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-300-Light.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-300-LightItalic.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-300-LightItalic.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-400-Book.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-400-Book.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-400-BookItalic.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-400-BookItalic.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-500-Medium.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-500-Medium.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-500-MediumItalic.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-500-MediumItalic.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-600-Semi.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-600-Semi.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-600-SemiItalic.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-600-SemiItalic.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-700-Bold.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-700-Bold.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-700-BoldItalic.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-700-BoldItalic.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-800-Hevy.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-800-Hevy.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-800-HevyItalic.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-800-HevyItalic.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-900-Black.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-900-Black.otf"
      "C+ '${config.services.forgejo.customDir}/public/assets/fonts/Jost-900-BlackItalic.otf' - forgejo forgejo - ${jostFonts}/fonts/Jost-900-BlackItalic.otf"
      # copy site/app logo files into Forgejo's public assets img folder
      "C+ '${config.services.forgejo.customDir}/public/assets/img/logo.svg' - forgejo forgejo - ${toString ../styling/PRG_logo.svg}"
      "C+ '${config.services.forgejo.customDir}/public/assets/img/logo.png' - forgejo forgejo - ${toString ../styling/PRG_logo.png}"
    ];

    # Fallback: one-shot systemd service to copy custom assets on activation (works even if tmpfiles isn't applied or for live testing)
    systemd.services."forgejo-custom-files" = {
      description = "Install Forgejo custom templates and assets into customDir";
      after = ["network.target"];
      serviceConfig = {
        Type = "oneshot";
        # Use bash -c to run a compact copy/install script that ensures dirs exist and files are owned by forgejo
        #           cp -a ${toString ../styling/forgejo/home.tmpl} ${config.services.forgejo.customDir}/templates/home.tmpl; \
        ExecStart = ''          ${pkgs.bash}/bin/bash -c "set -eu; \
                    install -d -m0755 -o forgejo -g forgejo ${config.services.forgejo.customDir}/public/assets/fonts; \
                    install -d -m0755 -o forgejo -g forgejo ${config.services.forgejo.customDir}/public/assets/css; \
                    install -d -m0755 -o forgejo -g forgejo ${config.services.forgejo.customDir}/templates/custom; \
                    cp -a ${mapleFonts}/fonts/MapleMonoNerd.ttf ${config.services.forgejo.customDir}/public/assets/fonts/MapleMonoNerd.ttf; \
                    cp -a ${toString ../styling/forgejo/header.tmpl} ${config.services.forgejo.customDir}/templates/custom/header.tmpl; \
                    cp -a ${toString ../styling/forgejo/theme-custom.css} ${config.services.forgejo.customDir}/public/assets/css/theme-custom.css; \
                    cp -a ${jostFonts}/fonts/* ${config.services.forgejo.customDir}/public/assets/fonts/ || true; \
                    cp -a ${toString ../styling/PRG_logo.svg} ${config.services.forgejo.customDir}/public/assets/img/logo.svg || true; \
                    cp -a ${toString ../styling/PRG_logo.png} ${config.services.forgejo.customDir}/public/assets/img/logo.png || true; \
                    chown -R forgejo:forgejo ${config.services.forgejo.customDir}"'';
      };
      wantedBy = ["multi-user.target"];
    };

    # Open ports in the firewall.
    networking.firewall.allowedTCPPorts = [30000];

    system.stateVersion = "25.11";
  };
}
