#!/bin/sh

qt_priv_cppflags () {
    version="$(pkg-config --modversion "$1")"
    set -- $(pkg-config --cflags-only-I "$1")
    for flag; do
        path="${flag#-I}"
        path="${path%/}"
        [ -d "${path}/${version}" ] || continue
        printf ' -isystem %s' "${path}/${version}"
        [ -d "${path}/${version}/${path##*/}" ] || continue
        printf ' -isystem %s' "${path}/${version}/${path##*/}"
    done
}

args="$0 $*"
[ $# -ge 2 ] || exit 1
src="$1"
dest="$2"
shift 2
all_flags=""
for pkg; do
    all_flags="${all_flags} $(qt_priv_cppflags "${pkg}")"
done

printf "// Code generated by \"%s\"; DO NOT EDIT.\n" "${args}" > "${dest}"
while read -r line; do
    set -- $line
    if [ "$1" = "//" ] && [ "$2" = "#cgo" ]; then
        if [ "$3" = "CPPFLAGS:" ] || [ "$4" = "CPPFLAGS:" ]; then
            printf "%s%s\n" "${line}" "${all_flags}"
            continue
        fi
    fi
    printf "%s\n" "${line}"
done <"${src}" >>"${dest}"
