intf_libs =

name = $regex.replace($project, 'cuda-', '')

source redist.build
define [see_through] import: group

./: libs{$name}: import{legal} import{$name} $intf_libs

redist{cuda_$name}: $src_root/manifest
archive{$cc.target.class-$cc.target.cpu-$version-archive.tar}: redist{cuda_$name}
extract{archive}: archive{$cc.target.class-$cc.target.cpu-$version-archive.tar}
import{$name}: extract{archive}: update = match
import{legal}: extract{archive}: update = match

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

  legal = [path] "$out_base/LICENSE"

  depdb dyndep \
    --dyn-target \
    --target-cwd "$o" \
    --target-what 'imported files' \
    --target-default-type 'legal' \
    --format lines \
    --file $d \
    -- \
      echo $legal >$d

  diag import $>

  for t : $filter_out($>, group)
    touch $path($t)
  end
}}
import{$name}:
{{
  o = $directory($>[0])
  d = $o/$name($>[0]).files

  find "$out_base/bin/" -type f -name "*" \
    | set -n l [paths]
  find "$out_base/lib/" -type f -name "*" \
    | set -n i [paths]
  i = $regex.filter_out_search($i, '.*static.*')
  find "$out_base/include/" -type f -name "*" \
    | set -n h [paths]

  depdb dyndep \
    --dyn-target \
    --target-cwd "$o" \
    --target-what 'imported files' \
    --target-default-type 'h' \
    --target-extension-type '=h' \
    --target-extension-type 'h=h' \
    --target-extension-type 'hpp=h' \
    --target-extension-type 'so=libs' \
    --target-extension-type 'dylib=libs' \
    --target-extension-type 'dll=libs' \
    --target-extension-type 'lib=libi' \
    --format lines \
    --file $d \
    -- \
      echo $regex.merge($l $i $h, '(.+)', '\1\n') >$d

  diag import $>

  for t : $filter_out($>, group)
    touch $path($t)
  end
}}

## create phony libs{<name>} such that we can export a
#  deterministic libs{} target, and generate a single
#  libi{<name>} from all extracted import libraries.
<libs{$(name).dll} libi{$(name).dll.lib}>:
{{
  n     = $name($>[0])
  ilibs = ($filter($<, libi))

  $effect($bin.ld.path) -DUMP -NOLOGO -HEADERS $path($ilibs[0]) \
   | sed -n -e 's/.*machine \((.*)\)/\1/p' \
   | set -w m
  m = ($m[0])

  diag $name($bin.ar.path) $ilibs $>

  # create a dummy libs{<name>} as this is only acting as
  # an 'alias' target, essentially creating a phony lib.
  touch "$path($>[0])"

  # combine all import libraries to one
  $effect($bin.ar.path) -NOLOGO "-OUT:$path($>[1])" \
                        "-NAME:$n" "-MACHINE:$m" $path($ilibs) >! 2>&1
}}


if ($cc.target.system == 'mingw32')
  c.loptions += -Wl,--export-all-symbols

# Export options.

lib{$name}:
{
  cc.type = cc
  cc.export.poptions = "-I$out_base/include"
  cc.export.libs = $intf_libs
}

lib/liba{**}: install = false

exe{*}:
{
  install         = bin/
  install.subdirs = true
}

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