#!/bin/sh -e

##
# This script prepares the 'packages.git' repository for use by
# the included scripts. It is not needed to build packages, but
# is useful for maintainers. The 'autobuilder' does require it.
#
# Re-run any time you pull from upstream or switch branches.
#

HERE="$(dirname $(readlink -f ${0}))";
BASE="${HERE}/..";

##
# Compile 'tsort' utility. Used to compute topological sort for
# building the world. Assumes GCC, yes, easy enough to change.
#
gcc -o "${HERE}"/tsort "${HERE}"/tsort.c -O3;

##
# Compile 'sgrep' utility. Used to traverse the index generated
# below.
#
gcc -o "${HERE}"/sgrep "${HERE}"/sgrep.c -O3;

##
# Build subpackage index. Used for resolving dependencies when
# a subpackage is used instead of its parent.
#
# MAINTAINERS: If repos renamed/added/removed, must update below.
#
for repo in system user legacy; do
    find "${BASE}/${repo}" -mindepth 1 -maxdepth 1 -type d | sort | while read k; do
    (
        ##
        # Source APKBUILD in a subshell to avoid contamination.
        #
        . "${k}/APKBUILD";

        ##
        # Print the package name, whether it has subdeps or not.
        #
        printf " %s " "${k##*/}";

        ##
        # Trim non-name bits from any declared subpackage(s).
        #
        for s in ${subpackages} ${provides} ${pkgname}; do
            case ${s} in
                *::*) t=${s%%:*}; ;;
                *:*) t=${s%%:*}; ;;
                *=*) t=${s%%=*}; ;;
                *) t=${s}; ;;
            esac
            printf " %s" "${t}";
        done | tr ' ' '\n' | sort | uniq | xargs | sed -e 's/$/ /';
    )
    done
#done | awk -v X=1 'NF>X'
# (uncomment this ^ to exclude packages with no subpackages
done > "${HERE}"/.index