# NixOS module snippet for the DeerFlow egress firewall.
#
# Copy the systemd.services block below into your /etc/nixos/configuration.nix
# (or import this file from there). After `sudo nixos-rebuild switch`, the
# unit `deerflow-firewall.service` is started automatically after Docker and
# stays "active (exited)" so the rules persist for the lifetime of dockerd.
#
# Activation order:
#   docker.service  ->  deerflow-firewall.service
#
# The unit pulls the script straight from the repo at
# /home/data/deerflow-factory/scripts/deerflow-firewall.sh — change the path
# below if you check the repo out somewhere else.
#
# Disable / remove:
#   sudo systemctl stop deerflow-firewall    # rules go down
#   sudo systemctl disable deerflow-firewall # no auto-start
#   ...then remove the block from configuration.nix and rebuild.
#
# Verify:
#   systemctl status deerflow-firewall
#   sudo /home/data/deerflow-factory/scripts/deerflow-firewall.sh status

{ config, pkgs, ... }:

{
  systemd.services.deerflow-firewall = {
    description = "DeerFlow container egress firewall";

    # Make sure dockerd has created the DOCKER-USER chain before we touch it,
    # and rerun the unit when docker restarts so our rules are reapplied.
    after = [ "docker.service" ];
    requires = [ "docker.service" ];
    partOf = [ "docker.service" ];

    wantedBy = [ "multi-user.target" ];

    path = [ pkgs.iptables pkgs.iproute2 pkgs.bash ];

    serviceConfig = {
      Type = "oneshot";
      RemainAfterExit = true;

      # Adjust this path if you store the repo elsewhere.
      ExecStart = "/home/data/deerflow-factory/scripts/deerflow-firewall.sh up";
      ExecStop  = "/home/data/deerflow-factory/scripts/deerflow-firewall.sh down";
    };
  };
}
