#
# 20_redundant_deps.awk
#
# Version 0.1 - 2024-04-14
# John McQuah <jmcquah at disroot dot org>
#
# Test if we have the same dependency more than once 
#  (inlined from 20_duplicated_deps.awk by Juergen Daubert)
#
# Test if any of the direct dependencies would also appear deeper in the deptree
#  (adapted from findredundantdeps by Johannes Winkelmann)

function find_deps(port) {
    CMD = ("prt-get quickdep " port " 2>&1")
    CMD |getline
    close(CMD)
    if ($0 ~ /could not be found:/) {
        return ""
    } else {
        NF = NF - 1
        return $0
    }
}

FILENAME ~ PKGFILE && loglevel_ok(WARN+INFO) {

    if ( $0 ~ /^#[[:space:]]+Depends on:/ ) {
        split($0, ac, /:[[:space:]]*/)
        split(ac[2], ad, /[[:space:]]*,[[:space:]]*|[[:space:]]+/)

        # Populate array au: only the direct dependencies (duplicates removed)
	delete au
        for (d in ad) {
	    if (ad[d] in au) {
	        if (loglevel_ok(WARN))
		    perror(WARN, "dependency listed more than once: " ad[d])
	    } else {
	        au[ad[d]]
	    }
        }

	if (! loglevel_ok(INFO)) { next }

        # Construct array bu: all the indirect dependencies
	delete bu
        for (u in au) {
            bd=find_deps(u)
            split(bd, be, /[[:space:]]+/)
            for (e in be) {
                bu[be[e]]
            }
        }

        # Test whether any element of au also appears in bu
        for (u in au) {
            if (u in bu) {
                perror(INFO, "redundant dependency: " u)
            }
        }
    }
}
