# Edit this configuration file to define what should be installed on
# your system.  Help is available in the configuration.nix(5) man page
# and in the NixOS manual (accessible by running 'nixos-help').
{
  config,
  pkgs,
  lib,
  ...
}: let
  home-manager = builtins.fetchTarball "https://github.com/nix-community/home-manager/archive/release-25.11.tar.gz";
in {
  # Add Lix instead of Nix
  nixpkgs.overlays = [
    (final: prev: {
      inherit
        (prev.lixPackageSets.stable)
        nixpkgs-review
        nix-eval-jobs
        nix-fast-build
        colmena
        ;
    })
  ];
  nix.package = pkgs.lixPackageSets.stable.lix;

  imports = [
    # Include the results of the hardware scan.
    ./hardware-configuration.nix
    (import "${home-manager}/nixos")
  ];

  # Bootloader - The given default one by NixOS is not to be trusted....
  boot.loader.grub.enable = true;
  boot.loader.grub.version = 2;
  boot.loader.grub.device = "/dev/sda";

  networking.hostName = "nixos-traefik"; # Define your hostname.
  # networking.wireless.enable = true;  # Enables wireless support via wpa_supplicant.

  # Configure network proxy if necessary
  # networking.proxy.default = "http://user:password@proxy:port/";
  # networking.proxy.noProxy = "127.0.0.1,localhost,internal.domain";

  # Set your time zone.
  time.timeZone = "Europe/Copenhagen";

  # Select internationalisation properties.
  i18n.defaultLocale = "en_AU.UTF-8";

  i18n.extraLocaleSettings = {
    LC_ADDRESS = "en_AU.UTF-8";
    LC_IDENTIFICATION = "en_AU.UTF-8";
    LC_MEASUREMENT = "en_AU.UTF-8";
    LC_MONETARY = "en_AU.UTF-8";
    LC_NAME = "en_AU.UTF-8";
    LC_NUMERIC = "en_AU.UTF-8";
    LC_PAPER = "en_AU.UTF-8";
    LC_TELEPHONE = "en_AU.UTF-8";
    LC_TIME = "en_AU.UTF-8";
  };

  # Enable Tailscale for secure remote access
  services.tailscale.enable = true;

  # Enable Seatd for Wayland sessions (needed for sway/seat management)
  services.seatd = {
    enable = true;
    logLevel = "info";
  };

  # Enable the gnome-keyring secrets vault (expose via DBus)
  services.gnome.gnome-keyring.enable = true;

  # Enable Sway window manager instead of GNOME
  programs.sway = {
    enable = true;
    wrapperFeatures.gtk = true;
  };

  # Use greetd as a greeter that launches sway (tuigreet example)
  services.greetd = {
    enable = true;
    settings = {
      default_session = {
        command = "${pkgs.tuigreet}/bin/tuigreet --time --cmd sway";
        user = "greeter";
      };
    };
  };

  # Security and polkit
  security.polkit.enable = true;

  # Keep GPU support available for Wayland compositors / applications
  hardware.graphics = {
    enable = true;
    enable32Bit = true;
  };

  # Keep allowing unfree packages
  nixpkgs.config.allowUnfree = true;

  # Passwordless sudo for wheel group (as in example.nix)
  security.sudo.wheelNeedsPassword = false;

  # Hardware U2F support (from example.nix)
  security.pam.u2f = {
    enable = true;
    settings = {
      authfile = "/etc/u2f_keys";
      cue = true;
      pinverification = 0;
      userpresence = 1;
    };
  };

  # SSH Agent authentication
  security.pam.sshAgentAuth.enable = true;

  # Automatic upgrades (from example.nix)
  system.autoUpgrade = {
    enable = true;
    dates = "daily";
    allowReboot = false;
  };

  # Enable Traefik service
  services.traefik = {
    enable = true;
    group = "acme"; # Add traefik to acme group so it can read certificates

    staticConfigOptions = {
      entryPoints = {
        web = {
          address = ":80";
          asDefault = true;
          http.redirections.entrypoint = {
            to = "websecure";
            scheme = "https";
          };
        };

        websecure = {
          address = ":443";
          asDefault = true;
          http.tls = {
            # Use the certificates from the file provider
            domains = [
              {
                main = "prg-radio.org";
                sans = ["*.prg-radio.org"];
              }
            ];
          };
        };
      };

      log = {
        level = "INFO";
        filePath = "${config.services.traefik.dataDir}/traefik.log";
        format = "json";
      };

      # Enable file provider for TLS certificates - This needs to re-watched to determine if we should add entries here or there
      #providers.file = {
      #  directory = "${config.services.traefik.dataDir}/conf";
      #  watch = true;
      #};

      api.dashboard = true;
      # Access the Traefik dashboard on <Traefik IP>:8080 of your server
      api.insecure = true;
    };

    dynamicConfigOptions = {
      # Configure TLS to use the ACME certificates
      tls.certificates = [
        {
          certFile = "/var/lib/acme/prg-radio.org/cert.pem";
          keyFile = "/var/lib/acme/prg-radio.org/key.pem";
        }
      ];

      # HTTP Routers
      http.routers = {
        forgejo = {
          rule = "Host(`git.prg-radio.org`)";
          service = "forgejo";
          entryPoints = ["websecure"];
          tls = {};
        };
      };

      # HTTP Services
      http.services = {
        forgejo.loadBalancer = {
          servers = [
            {url = "http://10.1.1.4:3000";}
          ];
        };
      };
    };
  };

  # ACME certificate configuration
  security.acme = {
    acceptTerms = true;
    defaults.email = "dtu.prg@gmail.com";
    certs."prg-radio.org" = {
      domain = "*.prg-radio.org";
      group = "acme"; # Use acme group
      dnsProvider = "cloudflare";
      environmentFile = "/home/traefikprg/cloudflare/cloudflare.env";
      # Reload traefik when certificate is renewed
      reloadServices = ["traefik.service"];
    };
  };

  # Ensure traefik service waits for ACME certificates
  systemd.services.traefik = {
    after = ["acme-finished-prg-radio.org.target"];
    wants = ["acme-finished-prg-radio.org.target"];
  };

  # Add extra system packages from example.nix (appended to existing list)
  environment.systemPackages = with pkgs; [
    wget
    helix
    fastfetch
    hyfetch
    pgadmin4
    atool
    httpie
    alacritty
    hyfetch
    macchina
    wayland
    wlroots
    maple-mono.NF
    wl-clipboard
    mako
    btop
    fastfetch
    lshw
    pciutils
    usbutils
    btrfs-progs
    e2fsprogs
    ntfs3g
    dosfstools
    os-prober
    arp-scan
    librewolf
    git
  ];

  # Enable rsync service (from example.nix)
  services.rsync.enable = true;

  # OpenSSH detailed settings (merge with existing openssh.enable = true)
  services.openssh = {
    enable = true;
    ports = [22];
    settings = {
      PasswordAuthentication = true;
      UseDns = true;
      PermitRootLogin = "no";
    };
  };

  # Keymap (carry over)
  services.xserver.xkb = {
    layout = "us";
    variant = "";
  };

  # NetworkManager (already enabled) -- keep existing config
  networking.networkmanager.enable = true;

  # Add the extra user from example.nix
  users.users.traefikprg = {
    isNormalUser = true;
    description = "NixOS PRG Traefik Service";
    extraGroups = ["acme" "networkmanager" "wheel" "seat"];
    packages = with pkgs; [];
  };

  # Home Manager user configuration for traefikprg (from example.nix)
  home-manager.users.traefikprg = {pkgs, ...}: {
    home.packages = [
      pkgs.atool
      pkgs.httpie
      pkgs.alacritty
      pkgs.hyfetch
      pkgs.macchina
      pkgs.wayland
      pkgs.wlroots
      pkgs.maple-mono.NF
      pkgs.wl-clipboard
      pkgs.mako
      pkgs.btop
    ];

    home.sessionVariables = {
      TERMINAL = "alacritty";
    };

    programs.zsh.enable = true;

    programs.alacritty = {
      enable = true;
      settings = {
        window = {
          opacity = 1.0;
          padding = {
            x = 10;
            y = 10;
          };
        };
        font = {
          normal = {
            family = "Maple Mono NF";
            style = "Regular";
          };
          bold = {
            family = "Maple Mono NF";
            style = "Bold";
          };
          italic = {
            family = "Maple Mono NF";
            style = "Italic";
          };
          bold_italic = {
            family = "Maple Mono NF";
            style = "Bold Italic";
          };
          size = 14.0;
        };
        colors = {
          primary = {
            background = "#1e1e2e";
            foreground = "#cdd6f4";
          };
        };
      };
    };

    programs.hyfetch = {
      enable = true;
      settings = {
        preset = "lesbian";
        mode = "rgb";
        lightness = 0.55;
        backend = "macchina";
        logo_size = "small";
        pride_month_disable = false;
        pride_month_shown = [];
        color_align = {mode = "horizontal";};
      };
    };

    home.stateVersion = "25.11";
  };

  # Attach the system to the IPFire network:  set a static IP on the Proxmox bridge (ens18)
  # Adjust `ens18` and the address below to your environment.
  networking.interfaces.ens18.ipv4.addresses = [
    {
      address = "10.1.1.250";
      prefixLength = 24;
    }
  ];
  networking.defaultGateway = "10.1.1.1";
  environment.etc."resolv.conf".text = ''
    nameserver 10.1.1.2
  '';

  # Open ports in the firewall.
  networking.firewall.allowedTCPPorts = [80 443];
  networking.firewall.allowedUDPPorts = [80 443];
  # Or disable the firewall altogether.
  # networking.firewall.enable = false;

  # This value determines the NixOS release from which the default
  # settings for stateful data, like file locations and database versions
  # on your system were taken. It‘s perfectly fine and recommended to leave
  # this value at the release version of the first install of this system.
  # Before changing this value read the documentation for this option
  # (e.g. man configuration.nix or on https://nixos.org/nixos/options.html).
  system.stateVersion = "25.11"; # Did you read the comment?
}
