#!/bin/sh

##########################################################################
#   Script description:
#       Print the value of a port/package make variable.
#
#   Arguments:
#       [-p prefix]   Defaults to prefix of active ports/pkgsrc tree
#
#   History:
#   Date        Name        Modification
#   2013-01-21  Jason Bacon Begin
##########################################################################

usage()
{
    printf "Usage: $0 [--base-dir dir] [--flavor flavor] category/${port_or_package} variable-name\n"
    exit 1
}


##########################################################################
#   Main
##########################################################################

if auto-using-pkgsrc; then
    make=$(auto-pkgsrc-make)
    port_or_package=package
    base_dir=`auto-pkgsrc-dir`
else
    make=make
    port_or_package=port
    case $(auto-ostype) in
    DragonFly|FreeBSD|OpenBSD)
	if [ -z "$PORTSDIR" ]; then
	    if [ $(uname) = FreeBSD ]; then
		base_dir=/usr/ports
	    elif [ $(uname) = DragonFly ]; then
		base_dir=/usr/dports
	    fi
	else
	    base_dir=$PORTSDIR
	fi
	;;
    
    *)
	printf "Cannot find pkgsrc dir.\n" >> /dev/stderr
	auto-unsupported-os $0
	exit 1
    esac
fi

if [ $# -lt 2 ]; then
    usage
fi

while [ $(echo $1 | cut -c 1) = '-' ]; do
    if [ $1 = '--base-dir' ]; then
	base_dir=$2
	shift
	shift
    elif [ $1 = '--flavor' ]; then
	flavor="FLAVOR=$2"
	shift
	shift
    else
	usage
    fi
done

case $# in
2)
    ;;
*)
    usage
    ;;
esac
port_dir=$1
variable=$2

if [ ! -d $base_dir/$port ]; then
    printf "No such ${port_or_package}: $base_dir/$port\n"
    exit 2
fi

cd $base_dir/$port_dir
if [ $(uname) = OpenBSD ]; then
    # FIXME: Ugly hack.  Look for a cleaner approach.
    tmp_makefile=Makefile.print-make-variable
    cp Makefile $tmp_makefile
    sed -e "/^.include/i\\
print-make-variable:\\
	@echo \${$variable}\\
\\
" Makefile > $tmp_makefile
    make -f $tmp_makefile print-make-variable
    rm -f $tmp_makefile
else
    # FIXME: Is this still relevant?
    # Prevent HAVE_GNOME from adding -gnome to PKGNAME
    # FIXME: OpenBSD make does not support -v
    ${make} $flavor WITHOUT_GNOME=yes -v $variable
fi
