#!/bin/bash
fphp=$(echo "$0" | sed 's#\.sh$#.php#');
fout=$(echo "$0" | sed 's#\.sh$#.out#');

flist=()
while (( "$#" )); do case "$1" in
	-x|--debug) debug=1;                                                    shift 1;;
	--no-save)  nosave=1;                                                   shift 1;;
	-o|--out)   fout=("$2");                                                shift 2;;
	-f|--file)  flist+=("$2");                                              shift 2;;
	--)                                                              shift 1; break;;
	-*|--*=)    echo "Error: Unsupported flag $1" >&2;                       exit 1;;
	*) flist+=("$1");                                                       shift 1;;
esac; done
if [[ "${#flist[@]}" -eq 0 ]]; then
	echo -n 'Searching files... ';
	while IFS= read -r -d $'\0' line; do flist+=("${line}"); done < <(find -type f -iname '*.php' -print0)
	echo -e "${R}${#flist[@]}${N} found. done."
fi
#if [[ ! -z "${debug}" ]]; then set -x; fi

rgrep -Hna -A 10 -Z --no-group-separator 'preg_[a-zA-Z0-9_]* *(' "${flist[@]}" |
	sed 's#\r##;s#\$preg_#$var#g;s#preg_quote#funct#g;s#^[^\x00]*\x0[0-9]\+\-#®#1' |
	sed ':a;N;$!ba;s#\n®#\x11#g;s#\x0#:#g' |
	grep -a 'preg_[a-zA-Z0-9_]* *(' |
	php -f "${fphp}" "${fout}" "${debug}"

# Comando para remover expressões vazias
# for n in $(php -f "${fout}" 2>&1 | grep 'Empty regular expression in' | grep -o '[0-9]\+$'); do sed -i "$n {s#^#//#}" "${fout}"; done