#!/bin/sh
#-*-mode:  sh -*-

# Copyright (c) 2007-2015, Aleksey Cheusov <vle@gmx.net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
#       copyright notice, this list of conditions and the following
#       disclaimer in the documentation and/or other materials provided
#       with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

set -e

export LC_ALL=C

: ${GREP_LIBEXECDIR:=/usr/pkg/libexec/psu}

usage (){
    cat 1>&2 <<'EOF'
pkg_grep_summary - output summaries about packages that matches
the specified condition, summaries are read from stdin.

USAGE: pkg_grep_summary -h
       pkg_grep_summary [opts] -e <field>
       pkg_grep_summary [opts] -E <field>
       pkg_grep_summary [opts] -m <field> <regexp>
       pkg_grep_summary [opts] -s <field> <string>
       pkg_grep_summary [opts] -S <field> <file>
       pkg_grep_summary [opts] -t <strategy> <field> <condition>
       pkg_grep_summary [opts]    <field> <awk_condition>
       pkg_grep_summary -T
  <field>         - PKGBASE, PKGNAME, PKGPATH, DEPENDS etc.
  <awk_condition> - Boolean expression written in AWK language
  <regexp>        - AWK regular expression
  <string>        - Text string
  <strategy>      - Search strategy. See -T for a list of available
                    search strategies.
OPTIONS:
  -h          display this message
  -i          ignore case
  -v          invert the sense of matching
  -f <fields> output only the specified fields, by default
              the whole summary is output
  -r          exit status is 1 if nothing was found
  -R          -r + "No matches found" is output to stderr

  -t          matches <field> using search strategy <strategy>
              and condition specified in <condition>
  -e          matches empty and absent fields,
              synonym to "-t empty"
  -E          matches non-empty fields,
              synonym to "-t nonempty"
  -m          matches <field> against regular expression <regexp>,
              synonym for "-t re"
  -s          matches <field> equal to <string>,
              synonym for "-t exact"
  -S          matches <field> equal to any string in <file>,
              one string per line,
              synonym for "-t strfile"

  -T          displays all search strategies available for -t and exits
EOF
}

strats=0
while getopts hivf:rRt:eEmsST f; do
    case "$f" in
	h)
	    usage;  exit 0;;
	e)
	    strategy=empty;;
	E)
	    strategy=nonempty;;
	s)
	    strategy=exact;;
	S)
	    strategy=strfile;;
	m)
	    strategy=re;;
	t)
	    strategy="$OPTARG";;
	T)
	    strats=$(($strats+1));;
	f)
	    fields="$OPTARG";;
	i)
	    ic=1;;
	r)
	    error=1;;
	R)
	    error=1
	    error_msg='No matches found';;
	v)
	    invert=1;;
	?)
	    echo "Bad option $1" 1>&2; exit 2;;
    esac
done
shift `expr $OPTIND - 1`

show_strats (){
    cat <<'EOF'
exact	Match exactly
prefix	Match prefixes
suffix	Match suffixes
substring	Match substring
word	Match separate words
first	Match the first word
last	Match the last word
re	POSIX 1003.2 (modern) regular expressions
strfile	Match the words from file
strlist	Match the specified words
awk	Match using AWK expression
empty	Match an empty string
nonempty	Match any non-empty string
kw	"keyword" match
EOF
}

if test "$strats" -gt 1; then
    show_strats
    exit 0
elif test "$strats" -eq 1; then
    strategies=`show_strats | cut -f1`
    echo $strategies
    exit 0
fi

test_argc (){
    if test "$1" -ne "$2"; then
	echo "pkg_grep_summary: invalid number of arguments." 1>&2
	exit 2
    fi
}

case "$strategy" in
    empty|nonempty)
	test_argc $# 1
	field="$1";;
    *)
	test_argc $# 2
	field="$1"
	string="$2";;
esac

case "$strategy" in
    empty|nonempty|exact|prefix|suffix|substring|first|last|word|re|strfile|strlist)
	;;
    awk|'')
	strategy=awk
	condition="$string";;
    kw|keywords)
	strategy=kw
	condition='match_keywords(fvalue)';;
    *)
	echo "Unknown search strategy: $strategy" 1>&2
	exit 2;;
esac

case "$strategy" in
    awk|kw)
	;;
    *)
	$GREP_LIBEXECDIR/grep_summary ${ic:+-i} -f "$fields" \
	    ${invert:+-v} ${error:+-r} ${error_msg:+-R} -t "$strategy" "$1" "$2"
	exit $?;;
esac

runawk -v ic="$ic" -v reqd_fields_="$fields" -v invert="$invert" \
       -v string="$string" -v strategy="$strategy" \
       -v error="$error" -v error_msg="$error_msg" \
-e '
#use "pkg_grep_summary.awk"
#use "xgetline.awk"
#use "str2regexp.awk"

BEGIN {
   if (strategy == "kw"){
      cnt_kw = split(string, arr_kw)
      for (i=1; i <= cnt_kw; ++i){
         if (i > 1)
            re_kw = re_kw "|"
         re_kw = re_kw str2regexp(arr_kw [i])
      }
      re_kw = "(" re_kw ")"
   }

   grep_summary__field="'"$field"'"
   keep_fields = (grep_summary__field == "" || grep_summary__field == ".")
}

function grep_summary__condition (){
   return '"$condition"'
}
'
