#!/bin/sh
# Copyright(c) 2010 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library in the file COPYING.LIB;
# if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
#
# @author Mladen Turk
#
#
# $1    package name
# $2    package spec
# $3    package base
#

getpackage_exit_code=0
xb_getpackage()
{
    o_name=false
    o_bver=false
    o_ctag=false
    o_srcp=false
    o_srca=false
    o_list=false
    for o
    do
        case "$o" in
        -*=*) a=`echo "$o" | $XB_GSED 's/^[-_a-zA-Z0-9]*=//'` ;;
           *) a='' ;;
        esac
        case "$o" in
            -n ) o_name=true;      shift ;;
            -b ) o_bver=true;      shift ;;
            -s ) o_srcp=true;      shift ;;
            -S ) o_srcp=true; o_srca=true;     shift ;;
            -t ) o_ctag=true;      shift ;;
            -a ) o_list=true;      shift ;;
            *  ) break ;;
        esac
    done
    if [ $# -lt 3 ]; then
        getpackage_exit_code=22
        return
    fi

    if [ ! -f "$2" ]; then
        getpackage_exit_code=22
        return
    fi
    if [ ! -d "$3" ]; then
        getpackage_exit_code=22
        return
    fi

    sIFS=$IFS; IFS=$XB_LF
    lines=`$XB_GSED -e 's/^[[:blank:]]*//' \
            -e '/^[[:blank:]]*$/d' \
            -e '/^[#;].*/d' "$2"`
    rv=""
    for l in $lines
    do
        IFS=$sIFS
        r=`echo $l | awk '{print $1}'`
        n=`echo $l | awk '{print $2}'`
        b=`echo $l | awk '{print $3}'`
        t=`echo $l | awk '{print $4}'`
        if $o_list; then
            case "$r" in
                C ) echo " rpmcvs   $n/$b $t" ;;
                B ) echo " brew     $n ${b}_${t}" ;;
                R ) echo " file     $n $t" ;;                
            esac
        else
            if [ "$n" = "$1" ]; then
                if $o_name; then
                    rv="$n"
                fi
                if $o_bver; then
                    rv="$b"
                fi
                if $o_ctag; then
                    rv="$t"
                fi
                if $o_srcp; then
                    rv=`cat "$3/$n/sources" | head -n 1`
                    if $o_srca; then
                        rv="$3/$n/$rv"
                    fi
                fi
                echo "$rv"
                break
            fi
        fi
    done
}

xb_getpackage $@
exit $getpackage_exit_code
