#!/usr/pkg/bin/runawk

# Copyright (c) 2010-2023, Aleksey Cheusov <vle@gmx.net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
#       copyright notice, this list of conditions and the following
#       disclaimer in the documentation and/or other materials provided
#       with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

############################################################

#env "LC_ALL=C"

#use "tmpfile.awk"
#use "power_getopt.awk"
#use "shquote.awk"
#use "xclose.awk"
#use "xgetline.awk"
#use "xsystem.awk"
#use "psu_funcs.awk"

############################################################
#.begin-str help
# pkg_summary2leaves - takes package summaries on input
#               and outputs summaries for leaf packages.
# usage: pkg_summary2leaves [OPTIONS] file1 <file2...>
# OPTIONS:
#   -h    display this help
#
#   -a    output only automatically installed leaves,
#         a field 'automatic' is expected on input
#   -u    output only user-installed leaves,
#         a field 'automatic' is expected on input
#
#   -r    select leaf packages recursively
#   -p    output PKGPATHs instead of summaries
#   -v    PKGPATHs or summaries of non-leaf packages are output
#.end-str
############################################################

BEGIN {
	if (getarg("h")){
		print_help()
		exit 0
	}

	rec       = getarg("r")
	auto_only = getarg("a")
	user_only = getarg("u")
	invert    = getarg("v")
	out_pkgs  = getarg("p")

	if (ARGV [1] == "-"){
		print "pkg_summary2leaves requires <files...>" > "/dev/stderr"
		exitnow(1)
	}

	for (i=1; i < ARGC; ++i){
		files = files " " shquote(ARGV [i])
	}
}

# build dependency graph
BEGIN {
	deps_fn = tmpfile()
	xsystem("pkg_summary2deps -dpnra " files " 2>/dev/null > " deps_fn)
}

# obtaining automatically installed packages
BEGIN {
	pipe = "cat " files " | pkg_grep_summary -v -e automatic"
	while ((pipe | getline) > 0){
		if (/^PKGPATH=/){
			pkgpath = substr($0, 9)
		}else if (/^PKGNAME=/){
			pkgname = substr($0, 9)
		}else if (NF == 0){
			auto [pkgpath ";" pkgname] = 0
			pkgpath = pkgname = ""
		}
	}
	xclose(pipe)
}

# read dependency graph
BEGIN {
	FS = "[ |]*"
	while (xgetline0(deps_fn)){
		assert(NF >= 1)
		if (NF > 1){
			for (i=1; i < NF; ++i){
				deps [$NF, ++deps_cnt [$NF]] = $i
				++chld_cnt [$i]
			}
		}
		chld_cnt [$NF] += 0
	}
	xclose(deps_fn)
}

# generate leaf package summaries
BEGIN {
	head = 1
	for (pkg in chld_cnt){
#		print "!!!", pkg, chld_cnt [pkg]
		if (!chld_cnt [pkg]){
			if (auto_only) {
				if (pkg in auto)
					queue [head++] = pkg
			} else if (user_only) {
				if (! (pkg in auto))
					queue [head++] = pkg
			} else {
				queue [head++] = pkg
			}
		}
	}

#	for (i=1; i < head; ++i){
#		print "queue:", queue [i]
#	}

	if (rec){
		for (tail=1; tail < head; ++tail){
			pkg = queue [tail]
			if (chld_cnt [pkg] == 0){
#				print "!", pkg
				deps_count = deps_cnt [pkg]
				for (i=1; i <= deps_count; ++i){
					dep = deps [pkg, i]

					if ((dep in auto) && 0 == --chld_cnt [dep]){
						queue [head++] = dep
#						print "dep:", dep
					}
				}
			}
		}
	}

	if (invert){
		for (i in queue){
			queue_a [queue [i]] = 0
		}
		head = 1
		delete queue
		for (i in chld_cnt){
			if (!(i in queue_a)){
				queue [head++] = i
			}
		}
	}

	for (i=1; i < head; ++i){
		if (out_pkgs)
			print pkgpana2pkgpath(queue [i])
		else
			pkgpaths = pkgpaths " " queue [i]
	}

	if (out_pkgs){
		exitnow(0)
	}else{
		gsub(/;/, ",", pkgpaths)
		system("cat " files " | pkg_grep_summary -t strlist PKGPANA " shquote(pkgpaths))
	}
}
