#!/bin/sh -e

##########################################################################
#   Script description:
#       Return success if a package is installed
#       
#   History:
#   Date        Name        Modification
#   2012-01-08  Jason Bacon Begin
##########################################################################

usage()
{
    printf "Usage: $0 [-p ports-dir] category/port\n"
    exit 1
}

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

case $# in
1)
    port=$1
    ;;
3)
    if [ $1 != '-p' ]; then
	usage
    else
	port=$3
    fi
    ;;
*)
    usage
    ;;
esac
    
case $(auto-ostype) in
FreeBSD)
    if [ `echo $port | awk -F / ' { print NF }'` != 2 ]; then
	usage
    fi
    
    name=`auto-print-make-variable $* PKGNAME`
    if [ $? != 0 ]; then
	printf "$name"
	exit 2
    fi
    
    major_name=${name%-*}
    if pkg info ${name} > /dev/null 2>&1; then
	printf "$name is installed.\n"
	return 0;
    elif pkg info $major_name > /dev/null 2>&1; then
	version=`pkg info $major_name | awk '$1 == "Version" { print $3 }'`
	installed="$major_name-$version"
	if [ $installed != $name ]; then
	    printf "$installed is installed (your ports tree contains $name).\n"
	fi
    else
	printf "$major_name is not installed.\n"
	return 1;
    fi
    ;;
    
*)
    printf "$0: Not supported on $(auto-ostype).\n"
    exit 1
    ;;

esac
