# SPDX-FileCopyrightText: 2021 Luke Granger-Brown <depot@lukegb.com>
#
# SPDX-License-Identifier: Apache-2.0

{ pkgs, depot, ... }:

let
  freeradiusConfig = pkgs.runCommandLocal "freeradius-config" (depot.ops.secrets.radius // {
    freeradius = pkgs.freeradius;
    raddb = ./raddb;
  }) ''
    cp -R $raddb $out
    chmod -R +w $out

    for f in $out/{radiusd,clients,proxy}.conf $out/mods-config/files/authorize; do
      substituteInPlace "$f" \
        --replace "{{FREERADIUS_LOC}}" "$freeradius" \
        --replace "{{JANET_ROAMING0_SECRET}}" "$janetroaming0" \
        --replace "{{JANET_ROAMING1_SECRET}}" "$janetroaming1" \
        --replace "{{JANET_ROAMING2_SECRET}}" "$janetroaming2" \
        --replace "{{WLC_SECRET}}" "$wlc" \
        --replace "{{USER_TESTUSER_PASSWORD}}" "$testuser" \
        --replace "{{USER_LUKEGB_PASSWORD}}" "$lukegb"
    done

    # can't check the config; it relies on things out-of-store
    # ${pkgs.freeradius}/bin/radiusd -C -sxl stdout -d $out
  '';
in {
  environment.systemPackages = [
    pkgs.freeradius
    depot.pkgs.eapol-test
  ];

  services.freeradius = {
    enable = true;
    configDir = freeradiusConfig;
  };

  users.users.radius = {
    group = "radius";
    extraGroups = [ "acme" ];
    isSystemUser = true;
  };
  users.groups.radius = {};
}