{ pkgs }:
let
  msys2-env = pkgs.stdenvNoCC.mkDerivation rec {
    name = "msys2-env";
    srcs = import ./msys2_packages.nix { inherit pkgs; };
    buildInputs = [ pkgs.gnutar pkgs.zstd ];
    phases = [ "installPhase" ];
    installPhase = (pkgs.lib.strings.concatStringsSep "\n" (["mkdir $out"] ++ (map (p: "tar xvf ${p} -C $out") srcs)));
  };
  silenceFontconfig = # silence flood of "Fontconfig error: Cannot load default config file: No such file: (null)"
    ''
    export FONTCONFIG_PATH=$HOME/fonts
    mkdir $FONTCONFIG_PATH
    cat > $FONTCONFIG_PATH/fonts.conf << EOF
    <fontconfig>
    </fontconfig>
    EOF
    '';
  wine-msys2-build = pkgs.writeShellScriptBin "wine-msys2-build"
    ''
    export HOME=`mktemp -d`
    export WINEDEBUG=-all
    export WINEPATH=Z:${msys2-env}/mingw64/bin
    ${silenceFontconfig}
    exec ${pkgs.wineWowPackages.stable}/bin/wine64 $@
    '';
in {
  makeMsys2Package = { name, version, src, depends }: pkgs.stdenvNoCC.mkDerivation {
    pname = "${name}-msys2-pkg";
    inherit version;
    nativeBuildInputs = [
      pkgs.pacman pkgs.fakeroot pkgs.libarchive pkgs.zstd pkgs.file
      wine-msys2-build
    ];
    inherit src;
    phases = [ "buildPhase" "installPhase" ];
    buildPhase =
      ''
      export DRV_VERSION=${version}
      cat > PKGBUILD << HEREDOC
      pkgbase="mingw-w64-${name}"
      pkgname="mingw-w64-x86_64-${name}"
      pkgrel=1
      depends=(
        ${pkgs.lib.concatStringsSep "\n" (map (depend: "\"${depend}\"") depends)}
      )
      source PKGBUILD.common
      HEREDOC
      ln -s ${./PKGBUILD.common} PKGBUILD.common
      ln -s $src source
      tar cfh source.tar source
      rm source
      makepkg --config ${./makepkg.conf} --nodeps
      '';
    installPhase =
      ''
      mkdir $out $out/nix-support
      cp *.pkg.tar.zst $out
      echo file msys2 $out/*.pkg.tar.zst >> $out/nix-support/hydra-build-products
      '';
  };
  makeMsys2Repos = constituents: pkgs.stdenvNoCC.mkDerivation {
    name = "msys2-repos";
    nativeBuildInputs = [ pkgs.pacman ];
    phases = [ "buildPhase" ];
    buildPhase =
      ''
      mkdir $out
      cd $out
      ${pkgs.lib.concatStringsSep "\n"
        (map (constituent: "ln -s ${constituent}/*.pkg.tar.zst .") constituents)}
      repo-add artiq.db.tar.gz *.pkg.tar.zst
      '';
  };
}