{ lib
, pkgs
}:

# this assumes github:tfc/nspawn-nixos nspawn-tarball.nix is mixed into it
nixosConfiguration:

let

  hostname = nixosConfiguration.config.networking.hostName;
  inherit (nixosConfiguration.config.nixpkgs) system;

  setup = pkgs.substituteAll {
    src = ./setup-nspawn.sh;
    isExecutable = true;
    inherit hostname;
  };

  inherit (nixosConfiguration.config.system.build) tarball;

in

pkgs.runCommandNoCC "nspawn-setup-${hostname}.sh" {
  nativeBuildInputs = with pkgs; [ makeself ];
} ''
  mkdir -p archive/
  ln -s ${setup} archive/setup.sh
  ln -s ${tarball}/tarball/nixos-system-${system}.tar.xz archive/nixos-${hostname}.tar.xz

  echo tarball: ${tarball}
  makeself --nocomp --follow archive/ $out "setup-nixos-nspawn-${hostname}" ./setup.sh
''
