#!/bin/sh
#
# cpsvndir: recursive directory copy excluding .svn sub dirs.

if [ -z "$1" -o -z "$2" ]; then
    echo "Usage: $0 source-dir destination-dir"
    exit -1
fi

# Some shells don't set EUID
if [ -z "$EUID" ]; then
    if [ -x /usr/bin/id ]; then EUID=`id -u` ;fi
    if [ -z "$EUID" ];     then EUID=$USER   ;fi
    if [ -z "$EUID" ];     then EUID=0       ;fi  # Will fail if not root
fi

# Do similarly for EGID
if [ -z "$EGID" ]; then
    if [ -x /usr/bin/id ]; then EGID=`id -g` ;fi
    if [ -z "$EGID" ];     then EGID=0       ;fi  # Will fail if not root
fi

BASE=$(basename "$1")
case "$BASE" in
    .|..|/)  BASE="" ;;
    *)       BASE="/$BASE" ;;
esac

SRC="$1"

case "$2" in
    /*) DEST="$2$BASE" ;;
    *)  DEST="$(pwd)/$2$BASE" ;;
esac

#echo "BASE=$BASE SRC=$SRC DEST=$DEST"

IFS='
'
if [ ! -z ${MYTHPYTHON} ]; then
    if [ ! -f ${MYTHPYTHON} ]; then
        MYTHPYTHON="/usr/bin/env ${MYTHPYTHON}"
    fi
fi

# Copy all files and directories except .svn
cd "$SRC"
for file in $(find . -name .svn -prune -or -print); do
    #echo "processing $file"
    if [ -d "$file" -a ! -L "$file" ]; then
        mkdir -p "$DEST/$file"
    else
        cp -pR "$file" "$DEST/$file"
        ext=${file##*.}
        if [ "x$ext" = "xpy" ]; then
            sed "1s%^#.*%#!${MYTHPYTHON}%" "$file" > "$DEST/$file"
#        elif [ "x$ext" = "xpl" ]; then
#            do some perly stuff
        fi
        chown -h $EUID:$EGID "$DEST/$file"
        chmod +r "$DEST/$file" &> /dev/null
    fi
done

exit 0

