#!/bin/sh

set -e

repository=/home/git/repositories
tmpdir=/tmp/xenomai-documentation

USAGE="$0 [ -q | -v ] [ -d ] [ -h ] installdir dirs

Extract Xenomai documentation tree for directories "dirs". Where dirs are taken
as subdirectories of git repository root. Extracted documentation trees
are copied as subdirectories of "installdir".

For instance:
$0 download.gna.org:/upload/xenomai/documentation xenomai-2.0

extracts the generated documentation from the xenomai-2.0 repository
and copy it to
download.gna.org:/upload/xenomai/documentation/xenomai-2.0

Options:
-q, --quiet    quiet, print only error messages, suitable for cron jobs.
-v, --verbose  verbose, git and rsync operations print file names.
-d, --debug    debug, print every command before actually running it.
-h, --help     print usage and exit.
"

ECHO=echo
GIT_CLONE="git clone"
RSYNC="rsync"

# Parse command line arguments.
while :; do
    case "$1" in
    # Really verbose, output details
    -v|--verbose) SVN=svn
	RSYNC="rsync -v"
	;;

    # Really silent, for cron jobs
    -q|--quiet) ECHO=:
	RSYNC="rsync -q"
	GIT_CLONE="git clone -q"
	;;

    # Debugging
    -d|--debug) set -x
	;;

    -h|--help) cat <<EOF
$USAGE
EOF
	exit 0
	;;

    *) break
       ;;
    esac
    shift
done


if test $# -lt 2; then
    cat <<EOF
$USAGE

Error: not enough arguments.
EOF
    exit 1
fi


installdir=$1; shift
if test "x$installdir" = x; then
    cat <<EOF
$USAGE

Error: empty installation directory.
EOF
    exit 1
fi

[ -d $tmpdir ] && rm -Rf $tmpdir
mkdir $tmpdir
cd $tmpdir

for dir in ${1+"$@"}; do
    $ECHO Checking out Xenomai directory $dir documentation...
    $GIT_CLONE $repository/$dir.git $dir
    $ECHO done.

    $ECHO Changing files and directories modes...
    find $dir/doc/generated $dir/doc/nodist | xargs chmod u=rwX,g=rwX,o=rX
    chmod u=rw,g=rw $dir/TROUBLESHOOTING $dir/README.INSTALL
    $ECHO done.

    $ECHO Copying to $installdir/$dir...
    mkdir -p $installdir/$dir
    $RSYNC -e ssh -prltgDz --delete --delete-after \
	$dir/doc/generated/ $dir/doc/nodist/ \
	$dir/README.INSTALL $dir/TROUBLESHOOTING \
	$installdir/$dir/
    $ECHO done.
done

cd ..
rm -Rf $tmpdir
