#!/usr/bin/bash

NOBANNER=1
batch_flag=""
if [ "${BATCH}" = 1 ]; then
    echo "Enabling batch mode."
    batch_flag="-b"
fi
. ../lib/functions.sh

[ "${1}" == "licenses" ] && AUDIT_LICENSE=1

# targets maps any valid package name to its build script.
declare -A targets
# fulltargets maps full package names to their build script.
declare -A fulltargets
declare -A licenses
TCNT=0
for build in */build*.sh
do
    for PKG in $(grep -v '##IGNORE##' $build | sed -e 's/^ +//' -e 's/ +#.+//' -e 's/=/ /g' -e 's/^.+make_package/make_package/g' | awk '{if($1=="PKG"){PKG=$2; print $2;} if($1=="make_package"){print PKG"="$2;}}')
    do
        if [ -n "`echo ${PKG} | grep '.='`" ] ; then
            [ -z "${AUDIT_LICENSE}" ] && continue
            MOG=`echo ${PKG} | sed -e 's/^.*=//'`
            PKG=`echo ${PKG} | sed -e 's/=.*$//'`
            LOCALMOG=`echo ${build} | sed -e 's:/.*$:/local.mog:'`
            [ -f $MOG ] || MOG=""
            [ -f $LOCALMOG ] || LOCALMOG=""
            LICENSE=`nawk -F "[ =]" '/"/{gsub("\"", "")} /^license/ {print $3;}' $MOG $LOCALMOG /dev/null | xargs`
            licenses+=([$PKG]=$LICENSE)
            TCNT=$(($TCNT + 1))
            print -f "."
        else
            targets+=([$PKG]=$build)
            fulltargets+=([$PKG]=$build)
            #
            # Repeatedly strip off leading components to generate all valid
            # names for this package.
            #
            while [[ $PKG =~ '/' ]]; do
                PKG=${PKG#*/}
                targets+=([$PKG]=$build)
            done
        fi
    done
done
[ -n "${AUDIT_LICENSE}" ] && echo

for manifest in */*.p5m
do
    for PKG in $(awk '/^set name=pkg.fmri/ {print $3;}' $manifest | sed -e 's/value=//' -e 's/.*\/\/[^\/]*\///g' -e 's/@.*//')
    do
        targets+=([$PKG]=$manifest)
    done
done

usage() {
    echo $0
    echo "    list [grep pattern]"
    echo "    licenses"
    echo "    build <pkg> | all"
    exit
}

bail() {
    echo $*
    exit
}

list() {
    PAT=${1-.}
    for target in "${!fulltargets[@]}"
    do
        if [[ "$PAT" = "." ]]; then
            echo " * $target"
        elif [[ -n $(echo "$target" | grep "$PAT") ]]; then
            echo " * $target"
        fi
    done | sort
}

build() {
    if [[ -z "${targets[$1]}" ]]; then
        bail "Unknown package: $1"
    fi
    DIR=$(dirname ${targets[$1]})
    pushd $DIR > /dev/null || bail "Cannot chdir to $DIR"
        PKGSRVR=$DEFAULT_PKGSRVR
        PKGPUBLISHER=$DEFAULT_PKGPUBLISHER
        PKGROOT=`pwd`/root
        if [[ -f environment ]]; then
            logmsg "--- Setting new environment"
            . environment
        fi
        SCRIPT=$(basename ${targets[$1]})
        if [[ -n $(echo $SCRIPT | grep ".p5m$") ]]; then
            echo "Found a manifest file. Preparing it for publishing."
            sed -e "s/@PKGPUBLISHER@/$PKGPUBLISHER/g; s/@RELVER@/$RELVER/g; s/@PVER@/$PVER/g;" < $SCRIPT > $SCRIPT.final
            if [[ -f root.tar.bz2 ]]; then
                echo "File archive found. Extracting..."
                bzip2 -dc root.tar.bz2 | tar xf - || \
                    bail "Failed to extract root.tar.bz2"
                echo "Publishing from $SCRIPT.final"
                pkgsend -s $PKGSRVR publish -d $PKGROOT $SCRIPT.final || \
                    bail "pkgsend failed"
                rm -rf $PKGROOT
            # In case we just have a tree of files and not a tarball
            elif [[ -d $PKGROOT ]]; then
                echo "Publishing from $SCRIPT.final"
                pkgsend -s $PKGSRVR publish -d $PKGROOT $SCRIPT.final || \
                    bail "pkgsend failed"
            # Else we just have a manifest to import
            else
                echo "Simple manifest to import... importing to $PKGSRVR"
                pkgsend -s $PKGSRVR publish $SCRIPT.final || \
                    bail "pkgsend failed"
                rm $SCRIPT.final
            fi
        else
            PATH=$PATH:. $SCRIPT -r $PKGSRVR $batch_flag || \
                logerr "Unable to run $SCRIPT"
        fi
    popd >/dev/null
}

licenses() {
    LCNT=0
    for target in "${!licenses[@]}"
    do
        if [[ -n "${licenses[$target]}" ]]; then
            echo " * $target     -> ${licenses[$target]}"
            LCNT=$(($LCNT + 1))
        fi
    done | sort
    if [ $LCNT -ne $TCNT ]; then
        echo
        echo "=== Packages missing license information ==="
        for target in "${!licenses[@]}"
        do
            if [[ -z "${licenses[$target]}" ]]; then
                echo " * $target"
            fi
        done | sort
    fi
}

DEFAULT_PKGSRVR=$PKGSRVR
DEFAULT_PKGPUBLISHER=$PKGPUBLISHER

case "$1" in
    list)
	list $2
	exit
	;;

    licenses)
	licenses
	exit
	;;

    build)
	shift
	tobuild=$*
	if [ -z "$tobuild" ] || [ "$tobuild" == "all" ]; then
		batch_flag="-b"
		for tgt in "${!fulltargets[@]}"; do
                        # Uncomment the echo line if you want to see a
                        # one-package-per-line status of what's building in
                        # /tmp/debug.<PID>.
                        # echo "Target = $tgt" >> /tmp/debug.$$
			build $tgt
		done
	else
		for tgt in $tobuild; do
			build $tgt
		done
	fi
        exit
	;;

    *)
	usage
	;;
esac

