{
  lib,
  runCommand,
  pkgs,

  name,
  packages,
  osId ? "patos",
  version ? null,
}:


let
  metadata = {
    ID = osId;
    VERSION_ID = osId;
    IMAGE_ID = name;
    IMAGE_VERSION = version;
  };

  metadataFile = lib.concatStringsSep "\n" (
    lib.mapAttrsToList (k: v: "${k}=${v}") (lib.filterAttrs (_: v: v != null) metadata)
  );

  doCopy =
    {
      drv,
      prefix ? "usr",
      path,
      destpath ? null,
    }:
    "do_copy ${prefix} ${drv} ${path}" + lib.optionalString (destpath != null) " ${destpath}";

in

runCommand name
  {
    passthru.name = name;
    inherit metadataFile;
    passAsFile = [ "metadataFile" ];

    buildInputs = [
      pkgs.erofs-utils
      pkgs.cryptsetup
    ];

  }
  ''
    do_copy () {
      local prefix="$1"
      local drv="$2"
      local path="$3"
      local destpath="''${4:-$path}"

      local srcfile
      local destdir
      local destfile
      srcfile="$drv/$path"
      destfile="$out/tree/$prefix/$destpath"
      destdir="$(dirname -- "$destfile")"

      mkdir -pv "$destdir"
      cp -Pv "$srcfile" "$destfile"

      chmod 755 "$destfile"
      patchelf --set-rpath /usr/lib $destfile || true
      patchelf --set-interpreter /lib/ld-linux-x86-64.so.2 $destfile || true
    }

    mkdir -p $out/tree

    ${lib.concatStringsSep "\n" (map doCopy packages)}

    # bake metadata into the structure
    if ! [ -f $out/tree/usr/lib/extension-release.d/extension-release."${name}" ]; then
      mkdir -p $out/tree/usr/lib/extension-release.d
      cat "$metadataFilePath" > $out/tree/usr/lib/extension-release.d/extension-release."${name}"
    fi

    pushd $out
    find tree -type d -exec chmod 0755 {} \;
    mkfs.erofs --all-root $name.raw tree/
    veritysetup format --root-hash-file $name.roothash $name.raw $name.verity
    # TODO: pcks7 signature
    # openssl smime -sign -nocerts -noattr -binary -in ${name}.roothash \
    #   -inkey key.pem -signer cert.pem -outform der -out ${name}.roothash.p7s
    rm -rf tree
    sha256sum * > SHA256SUMS
    # TODO: add gpg signature
    popd
  ''