#!/bin/bash

# This script reads filenames from STDIN and outputs any relevant provides
# information that needs to be included in the package.

if [ "$1" ]
then
   package_name="$1"
fi

[ -z "$OBJDUMP" ] && OBJDUMP=x86_64-w64-mingw32-objdump

# Get the list of files.

filelist=`sed "s/['\"]/\\\&/g"`

dlls_to_exclude="
    advapi32.dll
    cfgmgr32.dll
    comctl32.dll
    comdlg32.dll
    crypt32.dll
    ddraw.dll
    dnsapi.dll
    dsound.dll
    gdi32.dll
    gdiplus.dll
    glu32.dll
    glut32.dll
    imm32.dll
    iphlpapi.dll
    kernel32.dll
    mscms.dll
    mscoree.dll
    msimg32.dll
    msvcr71.dll
    msvcr80.dll
    msvcr90.dll
    msvcrt.dll
    mswsock.dll
    ole32.dll
    oleaut32.dll
    opengl32.dll
    psapi.dll
    rpcrt4.dll
    secur32.dll
    setupapi.dll
    shell32.dll
    shlwapi.dll
    user32.dll
    usp10.dll
    version.dll
    wininet.dll
    winmm.dll
    wldap32.dll
    ws2_32.dll
    wsock32.dll
"

exclude_pattern=""
for i in $dlls_to_exclude; do
    if test "$exclude_pattern" == ""; then
        exclude_pattern=$i;
    else
        exclude_pattern=$exclude_pattern"|"$i; 
    fi
done


dlls=$(echo $filelist | tr [:blank:] '\n' | grep -Ei '\.(dll|exe)$')
pcs=$(echo $filelist | tr [:blank:] '\n' | grep '\.pc$')
configs=$(echo $filelist | tr [:blank:] '\n' | grep 'config$')

for f in $dlls; do
    $OBJDUMP -p $f | grep 'DLL Name' | tr [:upper:] [:lower:] |
        grep -Eo '[-._\+[:alnum:]]+\.dll' |
        grep -Ev "$exclude_pattern" |
        sed 's/\(.*\)/mingw64(\1)/' 
done | sort -u

(
for g in $pcs; do
    dirname=`dirname $g`
	PKG_CONFIG_PATH=$dirname x86_64-w64-mingw32-pkg-config --print-errors --print-requires $g | awk '{ print "mingw64(pkg:"$1")", $2, $3 }'
	PKG_CONFIG_PATH=$dirname x86_64-w64-mingw32-pkg-config --print-errors --print-requires-private $g | awk '{ print "mingw64(pkg:"$1")", $2, $3 }'
	for h in `PKG_CONFIG_PATH=$dirname x86_64-w64-mingw32-pkg-config --libs-only-l $g | sed 's#\-l##g'`; do
		echo "mingw64(lib:$h)"
	done
done
for k in $configs; do
    for j in `PKG_CONFIG=x86_64-w64-mingw32-pkg-config $k --libs`; do
        case $j in
            -l*)
                echo $j | sed 's#\-l##g' | awk '{ print "mingw64(lib:"$1")" }'
		;;
            *)
                ;;
        esac
    done
done
) | sort -u
