{ config, lib, ... }:
let
  inherit (lib)
    mkIf
    mkEnableOption
    mkOption
    concatLists
    concatStringsSep
    ;
  inherit (lib.types)
    str
    listOf
    enum
    bool
    ;
  cfg = config.modules.services.tailscale;
in
{
  options.modules.services.tailscale = {
    enable = mkEnableOption "Tailscale";

    server = mkOption {
      type = str;
      default = "https://hs.ccnlc.eu";
    };

    isExitNode = mkOption {
      type = bool;
      default = false;
      description = "Enable if node should serve advertise itself as an exit node.";
    };

    tags = mkOption {
      type = listOf (enum [
        "client"
        "server"
      ]);
      default = [ ];
      apply = map (e: "tag:${e}");
    };

    defaultFlags = mkOption {
      type = listOf str;
      default = [ "--ssh" ];
    };

    extraFlags = mkOption {
      type = listOf str;
      default = [ ];
    };
  };

  config = mkIf cfg.enable {
    services.tailscale = {
      enable = true;
      extraUpFlags = concatLists [
        cfg.defaultFlags
        cfg.extraFlags
        (
          mkIf cfg.tags != [ ] [
            "--advertise-tags"
            (concatStringsSep "," cfg.tags)
          ]
        )
        (mkIf cfg.server [
          "--login-server"
          cfg.server
        ])
      ];
      useRoutingFeatures = mkIf cfg.isExitNode "server";
    };
  };

}
