import intf_libs = cuda-cudart%lib{cudart}

define [see_through] import: group

name = $string.replace($project, 'lib', '')

source redist.build

# NVIDIA ships the executables with no RPATH/RUNPATH.
extract_bin_rpath = '$ORIGIN/../lib'

manifest_json = [json_object] $json.load($src_base/manifest.json)
package_ver   = "$(version.major).$(version.minor).$(version.patch)"

pub_hdrs = [strings]
pub_incs = [dir_paths]
inc_root = [dir_path]
for d: [json_array] ($manifest_json["includeDirs"])
{
  dir = [string] $d
  pub_hdrs += "-I$out_base/$dir"

  # The first entry is the install root and becomes include/, the rest are
  # relative to it.
  #
  if ($empty($inc_root))
  {
    inc_root = [dir_path] $dir
    pub_incs += include/
  }
  else
  {
    rel = [string] $leaf([dir_path] $dir, $inc_root)
    pub_incs += "include/$rel"
  }
}

for plat: [json_object] ($manifest_json["platforms"])
{
  plat_key = $member_name($plat)
  enabled  = [bool] ($cc.target.cpu-$cc.target.class == $plat_key)
  archive{$name-$plat_key-$package_ver}: $src_base/manifest.json: include = $enabled
  extract{$name}: archive{$name-$plat_key-$package_ver}: include = $enabled
}

import{$name-headers}: extract{$name}: update = match

import{$name-headers}:
{{
  o = $directory($>[0])
  d = $o/$name($>[0]).files

  find "$out_base/include/" -type f -name "*" \
    | set -n f [paths]

  depdb dyndep \
    --dyn-target \
    --target-cwd "$o" \
    --target-what 'headers' \
    --target-default-type 'hxx' \
    --target-extension-type '=hxx' \
    --target-extension-type 'h=hxx' \
    --target-extension-type 'hpp=hxx' \
    --format lines \
    -- echo $regex.merge($f, '(.+)', '\1\n')

  diag import $>

  for f : $filter($>, hxx)
  {
    touch $path($f)
  }
}}

./: json{package}
json = [json_object] $json.load($src_base/package.json)
for plat: [json_object] ($json["platforms"])
{
  plat_key = $member_name($plat)
  enabled  = [bool] ($cc.target.cpu-$cc.target.class == $plat_key)
  plat_val = [json_object] $member_value($plat)

  for m: [json_object] ($plat_val["libs"])
  {
    n = $member_name($m)
    v = [json_object] ($member_value($m))

    # What the binary installed under this library's name actually is. It
    # cannot be derived from the file names: NVIDIA ships both real import
    # libraries and static archives of loader shims as lib/<name>.lib. build2
    # classifies the installed file by looking inside it, and the variant
    # declared here has to reach the same answer. If it does not, build2
    # manufactures a binless placeholder for the variant it cannot find, which
    # switches off the self -l skip when the generated pc file is loaded and
    # leaves the library its own prerequisite. See README-DEV.md.
    #
    linkage = [string] ($v["linkage"])

    assert ($linkage == 'shared' || $linkage == 'static' || \
            $linkage == 'binless') \
      "package.json: $plat_key $n linkage is not shared, static or binless"

    is_shared = [bool] ($linkage == 'shared')
    is_static = [bool] ($linkage == 'static')

    # build2 identifies this library's own entry in the generated pc file by
    # position, the first -l in Libs. The linked and shared loops prepend, so
    # for a library that has neither, that entry is the first archive and it
    # has to be this library's own.
    #
    ar0 = [string] ''
    has_link = [bool] false
    for x: [json_array] ($v["linked"])
      has_link = [bool] true
    for x: [json_array] ($v["shared"])
      has_link = [bool] true
    for x: [json_array] ($v["archives"])
    {
      if ($ar0 == '')
        ar0 = [string] $base($leaf([path] ([string] $x)))
    }

    if ($is_static && !$has_link)
      assert ($ar0 == ($regex.match($plat_key, '.+-windows') ? "$n" : "lib$n")) \
        "package.json: $plat_key $n archives[0] is not its own archive"

    # Keep clean = false. The prebuilt binaries below are declared targets
    # that no rule matches for clean, so cleaning through this library fails
    # with "no rule to clean ...". See build2 issue 463.
    #
    # Cost: b clean leaves the extracted payload in place (the downloaded
    # archives are unaffected, see README-DEV.md).
    #
    # The group, not a member: bin.lib selects which members are built and
    # installed, and bin.lib.suffix below renames the one that does not match
    # this library's linkage.
    #
    ./: lib{$n}:
    {
      include = $enabled
      clean   = false
    }

    # An importer picks the group member according to its own bin.lib, not
    # ours, so the variant that does not match here still gets built and
    # installed by anyone who depends on us. Its pc file would then sit next
    # to the right one and bring the placeholder back, so rename it out of the
    # way instead of suppressing it: for a binless member bin.lib.suffix feeds
    # nothing but the pc file name, since there is no binary of its own, and
    # the library itself stays installable. Only the section for the platform
    # being built may say this, the other section describes a platform where
    # the other variant is the right one.
    #
    if ($enabled && $is_shared)
      liba{$n}: bin.lib.suffix = '-unused'
    if ($enabled && $is_static)
      libs{$n}: bin.lib.suffix = '-unused'

    [rule_hint=cxx.link] \
    lib{$n}: import{$name-headers}: \
             extract{$name}:
    {
      include = $enabled
      update  = match
    }

    for b: [json_array] ($v["linked"])
    {
      dll  = [path] $out_base/($b["dll"])
      libi = [paths]
      for x: [json_array] ($b["libs"])
        libi += [paths] $out_base/$x

      <libs{$dll} libi{$libi}>: extract{$name}: include = $enabled
      lib{$n}: libs{$dll}: include = $enabled
      if $enabled
      {
        lib{$n}:
        {
          cc.export.libs =+ libs{$dll}
        }
      }
    }

    for s: [json_array] ($v["shared"])
    {
      so = [path] $out_base/$s
      <libs{$so}>: extract{$name}: include = $enabled
      lib{$n}: libs{$so}: include = $enabled
      if $enabled
      {
        if ($cc.target.class != 'windows')
        {
          lib{$n}:
          {
            cc.export.libs =+ libs{$so}
          }
        }
      }
    }

    # Shared libraries loaded at run time and never linked.
    for r: [json_array] ($v["runtime"])
    {
      so = [path] $out_base/$r
      <libs{$so}>: extract{$name}: include = $enabled
      lib{$n}: libs{$so}: include = $enabled
    }

    for a: [json_array] ($v["archives"])
    {
      ar = [path] $out_base/$a
      <liba{$ar}>: extract{$name}: include = $enabled
      lib{$n}: liba{$ar}: include = $enabled
      if $enabled
      {
        lib{$n}: cc.export.libs += liba{$ar}
      }
    }

    for d2: [json_array] ($v["depends"])
    {
      dep = [name] $d2
      lib{$n}: lib{$dep}: include = $enabled
      if $enabled
      {
        lib{$n}: cc.export.libs += lib{$dep}
      }
    }

    # Opaque resource files installed verbatim where upstream expects them.
    for r: [json_array] ($v["resources"])
    {
      res = [path] $out_base/$r
      <file{$res}>: extract{$name}: include = $enabled
      if $enabled
      {
        file{$res}: install = $directory([dir_path] $r)/
      }
      lib{$n}: file{$res}: include = $enabled
    }

    lib{$n}: $intf_libs: include = $enabled
    if $enabled
    {
      lib{$n}: cc.export.libs += $intf_libs
    }

    lib{$n}:
    {
      cc.type            = cc
      cc.export.poptions = $pub_hdrs
    }
    lib{$n}: cc.pkgconfig.include = $pub_incs
  }

  for m: [json_object] ($plat_val["exes"])
  {
    v = [json_object] ($member_value($m))
    p = [string] ($v["path"])

    # Every platform section declares this same program, and exe{name} and
    # exe{name.exe} are the same target: build2 matches on the target name,
    # and an unspecified extension matches any. But an extension, once
    # specified, is immutable, so a section for a platform we are not
    # building must not be the one that sets it. Drop the extension that
    # section recorded and write this platform's, so every section spells
    # the target identically.
    #
    n = [string] $member_name($m)
    t = "$base([path] $p)$redist_exe_ext"

    assert ("$leaf([path] $t)" == "$n$redist_exe_ext") "package.json: exe $n does not name its path $p"
    assert (!$enabled || "$t" == "$p") "package.json: exe $n path $p is not $t on this platform"

    ./: exe{$t}: include = $enabled
    exe{$t}: import{$name-headers}: extract{$name}: include = $enabled

    exe{$t}:
    {
      install         = $directory([dir_path] $p)/
      install.subdirs = true
    }

    for d2: [json_array] ($v["depends"])
    {
      dep = [name] $d2
      # install=false works around a build2 access violation installing an
      # exe{} with an ad hoc lib{} prerequisite (0.18.1, 0.19.0-a.0). Still
      # needed with the group rather than the member: b install segfaults
      # without it.
      exe{$t}: lib{$dep}:
      {
        include = $enabled
        clean = false
        install = false
      }
    }
  }
}

lib/liba{**}: install = false

include/h{**}:
{
  install         = include/
  install.subdirs = true
}

include/hxx{**}:
{
  install         = include/
  install.subdirs = true
}
