#!/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 base-dir] category/port\n"
    exit 1
}

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

case $# in
1)
    port=$1
    ;;
3)
    if [ $1 != '-p' ]; then
	usage
    else
	port=$3
    fi
    ;;
*)
    usage
    ;;
esac

if [ `echo $port | awk -F / ' { print NF }'` = 2 ]; then
    name=`auto-print-make-variable $* PKGNAME`
    if [ $? != 0 ]; then
	printf "$name"
	exit 2
    fi
elif [ `echo $port | awk -F / ' { print NF }'` = 1 ]; then
    name=$port
else
    usage
fi

if auto-using-pkgsrc; then
    major_name=${name%-*}
    if pkg_info ${name} > /dev/null 2>&1; then
	printf "$major_name is installed.\n"
	exit 0;
    elif pkg_info $major_name > /dev/null 2>&1; then
	version=`pkg_info $major_name | awk -F '[ :]' '$1 == "Information" { print $3 }'`
	installed="$major_name-$version"
	if [ $installed != $name ]; then
	    printf "$installed is installed (your pkgsrc tree contains $name).\n"
	fi
    else
	printf "$major_name is not installed.\n"
	exit 1;
    fi
else
    case $(auto-ostype) in
    FreeBSD)
	major_name=${name%-*}
	if pkg info ${name} > /dev/null 2>&1; then
	    printf "$name is installed.\n"
	    exit 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"
	    exit 1;
	fi
	;;

    OpenBSD)
        major_name=${name%-*}
        if pkg_info ${name} | grep -q "^Information for inst:${name}" > /dev/null 2>&1; then
            printf "$name is installed.\n"
            exit 0;
        elif pkg_info $major_name | grep -q "^Information for inst:${major_name}" > /dev/null 2>&1; then
            version=$(pkg_info $major_name | grep "^Information for inst:" | awk '{print $NF}' | cut -d'-' -f2-)
            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"
            exit 1;
        fi
        ;;
    
    *)
	printf "No FreeBSD ports or pkgsrc found.\n"
	exit 1
	;;
    
    esac
fi
