#!/usr/bin/awk -E
# Find redundant dependencies
# based on the bash script by Johannes Winkelmann <jw at tks6 dot net>

# $ cd /usr/ports/contrib
# $ findredundantdeps *
# $ findredundantdeps bmp

function parse_opt(i) {
    if (ARGV[i] ~ /^-[vsf]+$/) {
        split(ARGV[i],m,"")
        for (flag in m) {
            if (m[flag] == "s") { suggest=1 }
            else if (m[flag] == "f") { fix=1 }
            else { verbose=1 }
	}
    }
    else if (ARGV[i] ~ /^-.*/) { usage() }
    else { TARGETS[ARGV[i]] }
}

function usage() {
    print "usage: findredundantdeps [-v|-s|-f] <port>"
    exit
}

BEGIN {
  for (i=1; i<ARGC; i++) { parse_opt(i) }
  delete ARGV
  if (typeof(TARGETS) != "array") { usage() }

  PG_VERSION="prt-get version"
  while ((PG_VERSION | getline) > 0) {
    if ($2 ~ /5.19.[1-6]/) 
      {DEPTREE="prt-get deptree 2>&1 "}
    else
      {DEPTREE="prt-get --config-set='softdeps no' deptree 2>&1 "}
  }

  for (t in TARGETS) {
    while ((DEPTREE t | getline) > 0) {
      if ($0 ~ /not found/) { invalid[t] }
      else if ($0 ~ /^...[[:space:]]{3}[a-z].*[^>]$/) {dd[t][$NF]}
      else if ($0 ~/^...[[:space:]]{4}.*[^>]$/) {id[t][$NF]}
      else if ($0 ~ /^...[[:space:]]{3}[a-z].*-->$/) {dd[t][$(NF-1)]}
      else if ($0 ~/^...[[:space:]]{4}.*-->$/) {id[t][$(NF-1)]}
    }
    if (t in invalid) {
      print(t " not found in the active collections.")
      continue
    }
    for (i in dd[t]) { if (i in id[t]) { rd[t][i] } else { dc[t][i] } }
    if (typeof(rd[t]) == "array") {
      nr = asorti(rd[t],rp)
      printf "Redundant deps for %s are: ", t
      for (j in rp) {printf "%s ", rp[j]}
      nc = asorti(dc[t],dp)
      for (c=1; c<=nc; c++) { right[t]=(right[t] " " dp[c]) }
      if (suggest==1) {
        printf "\nRight is: # Depends on:%s\n", right[t]
      }
      if (fix==1) {
        while (("prt-get path " t | getline) > 0) { Pkgfile=("\"" $0 "/Pkgfile\"") }
        system("sed 's/^# Depends on:.*/# Depends on:" right[t] "/' -i.orig " Pkgfile)
	print("Fixed " t)
      }
    } else {
      if (verbose==1) {print(t " is fine.")}
    }
  }
}
