#!/usr/bin/perl -w
# ex=8
# vim:sts=4
# vim:sw=4
#
# Robert P. Gleeson 
# http://virtus.ath.cx/~rg/p_seek/ 
#
# A Perl script that searchs through the FreeBSD ports collection for an
# individual port. (Much like make search name/key except additional features
# are offered). 
#

use strict; 

if ( !defined($ARGV[0]) ) {
    print "Invalid syntax", "\n";
    print "p_seek [options] port-name", "\n";
    exit 1;
}

local *INDEX;
open(INDEX, "/usr/ports/INDEX") or
    die "Couldn't open INDEX for reading", "\n", "$!", "\n";
my @p_index  = <INDEX>;
close INDEX;

#
# Return one result.  And most likely will return the *exact* port you searched for because of the regex epr usage of ^.
#
sub __1  {
    print "$_[0]", "\n";
    print "x--------------------------------------------------------------------------x", "\n";
    print "| Port        :       $_[0] ", "\n";
    print "| Location    :       $_[1]", "\n";
    print "| Description :       $_[2]", "\n";
    print "| Maintainer  :       $_[3]", "\n";
    print "x--------------------------------------------------------------------------x", "\n\n";
	
    exit 0;
}

sub __longdescrip  {
    local *DESCRIP;
    open(DESCRIP, "$_[3]") or
	die "Couldn't open $_[3] for reading" . "\n" . "$!" . "\n";
    my @DESCRIP  = <DESCRIP>;
    close(DESCRIP);

    print "$_[0]", "\n";
    print "x--------------------------------------------------------------------------x", "\n";
    print "| Port                 :       $_[0] ", "\n";
    print "| Location             :       $_[1]", "\n";
    print "| Detailed Description :       ", "\n";
    for ( my $i = 0; $#DESCRIP >= $i; $i++ ) {
	chomp ( $DESCRIP[$i] ) ;
	print "| $DESCRIP[$i]", "\n";
    }
    print "| Maintainer           :       $_[2]", "\n";
    print "x--------------------------------------------------------------------------x", "\n\n";
}

for ( my $i = 0; $#p_index > $i; $i++ ) {
    my ( $port , $path , $base, $short_descrip, $descrip_loc, $maintainer, $rest ) = split(/\|/, $p_index[$i], 7);
    
    # Returns the first result and exits.
    if ( $ARGV[0] eq "-1" && $port =~ /^$ARGV[1]/ ) {
	__1($port, $path, $short_descrip, $maintainer);
    }
    if ( $port =~ /$ARGV[0]/ && !defined($ARGV[1]) ) {
	print "$port", "\n";
	print "x--------------------------------------------------------------------------x", "\n";
	print "| Port        :       $port ", "\n";
	print "| Location    :       $path ", "\n";
	print "| Description :       $short_descrip", "\n";
	print "| Maintainer  :       $maintainer", "\n";
	print "x--------------------------------------------------------------------------x", "\n\n";
	
    
    }
    if ( $ARGV[0] eq "-d" && $port =~ /$ARGV[1]/ ) {
	__longdescrip($port, $path, $maintainer, $descrip_loc);
    }   
}
