#!/usr/local/bin/perl
#set this to the name and path of LSM file.  
$LSMFILE = "/usr/local/lib/LSM.gz";
#set this to name of program to unzip LSMFILE
$UNZIPPER = "gunzip -c";
# The pager program to use
$PAGER = "less -r";

require 5.000;

use Getopt::Std;
use File::Basename;

$/ = "\nEnd";

sub printhelp {
my $prog = basename($0);
    print STDERR <<EOT
$prog does a case insensitive search of the Linux Software Map.
The options are:
	-d: Search only the Description field.
	-t: Search only the Title field.
	-k: Search only the Keywords field.
        -h: Get this help screen.
	regexpression: A regular expression to search for.
Default is to search every line.
EOT
}

sub highlight {
    local ($string, $pattern) = @_;
    $string =~ s/\b\w*$pattern\w*\b/"\e\[1m" . $& . "\e\[0m"/ieg;
    return $string;
}

sub dosearch {
    open(PAGER, "| $PAGER") or die "Can't open pipe to $PAGER,";
    open(LSMFILE, "$UNZIPPER $LSMFILE |") or die "Can't open $LSMFILE\n";
    select PAGER;

# if no options were given, do it the fastest way
    if (!$options{'title'} && !$options{'description'}
	&& !$options{'keywords'})
	{
	    # This actually reads in a whole record at a time, up to a line
	    # beginning with /^End/.  Because I set $/ to "\nEnd".
	    while (<LSMFILE>) {
		if (/$Pattern/i) {
		    $_ = &highlight($_, $Pattern); 
		    print;	# prints record to the PAGER 
		} 
	    }
	} else {		# else process options.
	    while (<LSMFILE>) {
		$found = 0;
		if ($options{'title'}) {
		    if (/\nTitle\:.*?\n(?=[\w-]+\:)/s) {
			$tmp = $&;
			if ($tmp =~ /$Pattern/i) {
			    s/\Q$tmp\E/highlight($&, $Pattern)/e;
			    $found = 1;
			}
		    }
		}
		if ($options{'description'}) {
		    if (/\nDescription\:.*?\n(?=[\w-]+\:)/s) {
			$tmp = $&;
			if ($tmp =~ /$Pattern/i) {
			    s/\Q$tmp\E/highlight($&, $Pattern)/e;
			    $found = 1;
			}
		    }
		}
		if ($options{'keywords'}) {
		    if (/\nKeywords\:.*?\n(?=[\w-]+\:)/s) {
			$tmp = $&;
			if ($tmp =~ /$Pattern/i) {
			    s/\Q$tmp\E/highlight($&, $Pattern)/e;
			    $found = 1;
			}
		    }
		}
		if ($found) {
		    print;
		}
	    }			# while
	}			# else
    
    close LSMFILE;	      
    close PAGER;
}


# Main program
getopts('tdkh') or $opt_h = 1;

if ($opt_h) {			# help option
    &printhelp;
    exit 1;
}

$options{'title'}       = $opt_t ? $opt_t : 0;
$options{'description'} = $opt_d ? $opt_d : 0;
$options{'keywords'}    = $opt_k ? $opt_k : 0;

if ($#ARGV >= 0) {
    $Pattern = shift;
    &dosearch;
} else {
    &printhelp;
}
