#!/bin/bash
##
##  This file is part of pyFormex 0.8.5  (Sun Dec  4 21:24:46 CET 2011)
##  pyFormex is a tool for generating, manipulating and transforming 3D
##  geometrical models by sequences of mathematical operations.
##  Home page: http://pyformex.org
##  Project page:  http://savannah.nongnu.org/projects/pyformex/
##  Copyright 2004-2011 (C) Benedict Verhegghe (benedict.verhegghe@ugent.be) 
##  Distributed under the GNU General Public License version 3 or later.
##
##
##  This program is free software: you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation, either version 3 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##
##  You should have received a copy of the GNU General Public License
##  along with this program.  If not, see http://www.gnu.org/licenses/.
##
# 
script=$(basename $0)
config=~/.pyformex/search.conf
SEARCH=pyformex-search
REPLACE=pyformex-replace

syntax() {
    cat <<EOF
Usage: ${SEARCH} [-a] [OPTION]... SEARCH
       ${REPLACE} [-a] [OPTION]... SEARCH TARGET REPLACE

${SEARCH}: searches for a regex (or string) SEARCH in all the Python files 
  of pyFormex and possibly in other configured (Python or other) files. 
  The matching file names and lines are displayed.
  Any OPTIONs (other than -a) are passed to the grep command which is 
  used in the background. Some very useful options:
  -F: interpretes SEARCH as a literal string (default is regex)
  -i: do a case insensitive search 

${REPLACE}: searches the same files for SEARCH, and in all matching 
  lines it replaces the string TARGET with REPLACE.
  Any OPTIONs (other than -a) are disregarded. 

Options:
-a : Should be the first and a separate option: if specified, the directories
     specified in the user configuration file:
       ~/${config}
     will also be searched. This configuration file holds a line 
       myfiles="list of paths"
     where list of paths is a blank separated list of paths relative
     from the place where the script is installed.

EOF
}


# These are the default pyformex paths that are searched

pyformexdir=pyformex
files=$(echo $pyformexdir/pyformexrc $pyformexdir/*{,/*,/*/*}.py)

if [ "$1" = "-a" ]; then
    shift
    echo $config
    [ -f "$config" ] && {
	. $config
	files="$files $myfiles"
    }
fi

search=$1
[ -n "$search" ] || { syntax; exit; }


cd $(dirname $0)

case "$script" in
    ${SEARCH} | searchpy) 
	grep "$@" $files ;;
    
    ${REPLACE} | changepy) 
	target=$2
	replace=$3
	[ -n "$target" ] && sed -i "/$search/s|$target|$replace|" $files
	;;

esac

