#!/bin/sh
#

# -----------------------------------------------------------------------------
print_usage()
{
    echo
    echo "Usage: $program_name <pattern> [evt-log-name]"
    echo ""
    echo "$program_name will parse the output of:"
    echo -e "\tevt_show details [evt-log-name]"
    echo "and will display any records that match the provided pattern."
    echo
}

# -----------------------------------------------------------------------------
create_awk_script()
{
    local filename=$1
    local pattern=$2

cat > $filename <<EOF
# auto-generated awk script
# parses evt_show details output for "$pattern"
BEGIN {
  output_record_count = 0;
  exit_code           = 0;

  RS="Event Record Number:";
  FS="\n";
  #print "matching $pattern"
}

# MAIN
{
  # The first record should be the current timestamp, so always display it
  if ( NR == 1)
    printf("%s", \$0);
}

/$pattern/ {
  printf("%s%s", RS, \$0);
  output_record_count++;
}

END {
  # On error conditions, don't print a summary.
  if (exit_code)
    break

  # indicate if there were no matches
  if (output_record_count) {
    #printf("%d matches\n", output_record_count);
  } else {
    printf("no matches\n");
  }
}
EOF

}

# -----------------------------------------------------------------------------
# main
{
    program_name=$(basename $0)
    tmp_awk_script="/tmp/evt_grep.$$"
    match_pattern=""
    log_name=""

    # Must specify a pattern for matching
    if [ "$#" -lt "1" ] ;  then
        echo "ERROR: missing parameters"
        print_usage
        exit 1
    else
        match_pattern=$1
    fi

    # Check for optional log name parameter
    if [ "$#" -gt "1" ] ; then
        log_name=$2
    fi

    # Check for too many parameters
    if [ "$#" -gt "2" ] ; then
        echo "ERROR: too many parameters"
        print_usage
        exit 1
    fi

    create_awk_script $tmp_awk_script $match_pattern
    
    evt_show details $log_name | awk -f $tmp_awk_script | more
    return_value=$?

    rm $tmp_awk_script

    exit "$return_value"
}
