#!/usr/bin/env bash

# Search through the file contents in the specified directory (or the current
# directory if not given), and below, for lines that match the given regular
# expression.

# This file is part of Scripnix. Copyright 2017 Dave Rogers <info@yukondude.com>. Licensed under the GNU General Public License, version 3.
# Refer to the attached LICENSE file or see <http://www.gnu.org/licenses/> for details.

scriproot=$(whereis-scripnix)
source "${scriproot}/conf/bin.bash"
check_arg_count ${0} ${#} 1 2 '[<directory>] <regexp>' ${1}

if [ ${#} -eq 2 ] ; then
    directory="${1}"
    regexp="${2}"
else
    directory="."
    regexp="${1}"
fi

gfind=$(gnu_equivalent 'find')
gsort=$(gnu_equivalent 'sort')
gxargs=$(gnu_equivalent 'xargs')
gsed=$(gnu_equivalent 'sed')

# Jump through hoops to find the regexp in all files, excluding RCS gunk. Use null-terminated lines throughout to avoid problems with
# filenames containing quotes. Trim any leading whitespace from the matching line.
$gfind "${directory}" ${FIND_PATH_EXCLUDE} -or -type f -print0 | \
    $gsort --zero-terminated | \
    $gxargs -I{} --null egrep --ignore-case --line-number --with-filename "${regexp}" {} | \
    $gsed --regexp-extended 's/:[[:space:]]+/:/'
