# Thanks @ kloenk (@kloenk@catcatnya.com) for making this for me at MRMCD 2024 :33
{ pkgs-stable, ... }:
let
  caDir = "/var/lib/easyroam";
  uuid = "821ad781-76a3-447f-a2e8-c7f18a1df3bc";
in
{
  systemd.services.easyroam = {
    requires = [ "NetworkManager.service" ];
    after = [ "NetworkManager.service" ];
    requiredBy = [ "network-online.target" ];
    path = with pkgs-stable; [
      networkmanager
      openssl
      gnused
    ];
    script = ''
      set -x
      openssl pkcs12 -password pass: -in ${caDir}/my_easyroam_cert.p12 -legacy -nokeys | openssl x509 > ${caDir}/easyroam_client_cert.pem
      cn=$(openssl x509 -noout -subject -in ${caDir}/easyroam_client_cert.pem -legacy | sed 's/.*CN = \(.*\), C.*/\1/')
      openssl pkcs12 -legacy -password pass: -in ${caDir}/my_easyroam_cert.p12 -nodes -nocerts | openssl rsa -aes256 -passin pass: -passout pass:meow -out ${caDir}/easyroam_client_key.pem
      openssl pkcs12 -password pass: -in ${caDir}/my_easyroam_cert.p12 -legacy -cacerts -nokeys > ${caDir}/easyroam_root_ca.pem

      nmcli connection modify --temporary uuid ${uuid} 802-1x.identity "$cn"
    '';
    serviceConfig = {
      Type = "oneshot";
    };
  };

  networking.networkmanager.ensureProfiles.profiles.eduroam = {
    "802-1x" = {
      ca-cert = "${caDir}/easyroam_root_ca.pem";
      client-cert = "${caDir}/easyroam_client_cert.pem";
      domain-suffix-match = "easyroam.eduroam.de";
      eap = "tls;";
      identity = "meow";
      private-key = "${caDir}/easyroam_client_key.pem";
      private-key-password = "meow";
    };
    connection = {
      id = "eduroam";
      type = "wifi";
      inherit uuid;
    };
    ipv4 = {
      method = "auto";
    };
    ipv6 = {
      addr-gen-mode = "default";
      method = "auto";
    };
    proxy = { };
    wifi = {
      mode = "infrastructure";
      ssid = "eduroam";
    };
    wifi-security = {
      key-mgmt = "wpa-eap";
    };
  };
}
