{ config, pkgs, ... }:

let
  inherit (pkgs) lib writeScript runtimeShell;
  gcroots = "/nix/var/nix/gcroots/mirror";

  mkMirrorService = name: url: {
    tmpfiles.rules = [
      "d ${gcroots}/${name} 0700 nixmirror nogroup - -"
    ];

    services."mirror-${name}" =
    let root = "${gcroots}/${name}"; in {
      path = with pkgs; [ coreutils curl xz findutils config.nix.package ]; 
    
      script = ''
        [ -d "${root}.old" ] && rm -r "${root}.old"
        [ -d "${root}.new" ] && rm -r "${root}.new"
        mkdir -p "${root}"{,.new}

        curl -sL ${lib.escapeShellArg url} \
          | xz -d \
          | xargs basename -a -- > ${root}.paths

        xargs -a ${root}.paths -I{} touch "${root}.new/{}"
        xargs -a ${root}.paths -P20 -L8 -I{} nix-store -r -- "${builtins.storeDir}/{}"

        mv -- "${root}" "${root}.old"
        mv -- "${root}.new" "${root}"
        rm -r -- "${root}.old"
      '';
    
      serviceConfig = {
        User = "nixmirror";
        Group = "nogroup";
        LimitNOFILE = 65536;
      };

      startAt = "03:14";
    };
  };
in {
  users.users.nixmirror.isSystemUser = true;

  systemd = lib.mkMerge [
    (mkMirrorService "stable" "https://nixos.org/channels/nixos-19.03/store-paths.xz")
    (mkMirrorService "unstable" "https://nixos.org/channels/nixos-unstable/store-paths.xz")
  ];
}