#!/bin/sh
#
#     /usr/local/bin/global
#
#     Execute a command in the current directory and its subdirectories
#
#     Written at Nov 1998 by Ilya Evseev
#     Contact e-mail: evseev@csa.ru
#

# -- Exit codes --

E_SYNTAX=-1
E_STOP=-2
E_READ=-3

# -- Variables --

_nonstop=0       #  1 = don't stop after failed command
_quiet=0         #  1 = don't echo ames of processed dirs
_prompt=0        #  1 = prompt before processing of next dir

# -- Print usage and exit --

syntax ()
{
    echo ""
    echo "Syntax: global [-i] [-q] [-p] command command_args ..."
    echo "  -i   ignore exit codes"
    echo "  -q   don't print directory name before processing"
    echo "  -p   prompt before processing of next directory"
    echo ""
    exit ${E_SYNTAX}
}

# -- Perform command in current dir --

one_dir ()
{
    #  Prompt Yes/No
    if [ "${_prompt}" = "1" ]
    then
        echo -n "global: press 'Y' to process `pwd`..."
        read i || exit ${E_READ}
        test $i != "y" -a $i != "Y" && return
        echo
    fi

    #  Display directory name
    test "${_quiet}" = "1" || echo global: `pwd`

    #  Execute command. Immediate exit, if command is failed
    #echo DEBUG: Execute "$@" in `pwd` ...
    $@ || test "${_nonstop}" = "1" || exit ${E_STOP}

    #  Recursively process all subdirectories
    for i in * ; do
        if [ -d $i ] ; then
            if [ -r $i -a -x $i ]
            then
                cd $i
                one_dir "$@"
                cd ..
            else
                echo global: $i: permission denied >/dev/stderr
            fi
        fi
    done
}

# -- Parse command line --

for i in $@ ; do
    case "$i" in
        '-i')  shift;  _nonstop=1  ;;
        '-q')  shift;  _quiet=1    ;;
        '-p')  shift;  _prompt=1   ;;
        *) break ;;
    esac
done
test $# -eq 0 && syntax

# -- Start execution --

eval one_dir "$@"
exit $?
