#!/bin/sh
#
# $Id$
#
# Run an OSGi-runner from a test harness directory bootstrapped with
#
#   osgi-runner-test-setup <path>
#

DEBUG_OPTS=

while test $# -gt 1
do
	case "$1" in
		--debug)
            DEBUG_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8002,server=y,suspend=n"
            echo '***** '"Will activate java remote debugger support on port 8002."
			shift 1;;
		*)
			echo "Unknown option: $1"
            break
	esac
done


if test $# -ne 1
then
    echo "Usage: $0 [--debug] <path>"
    echo "  <path> is the directory containing etc et al for a test osgi-runner"
    echo "  ---debug activates the java debug server listening on port 8002"
    exit 64
fi

dir=$1
absdir=$(cd $dir && pwd)

echo '***** '"Running test osgi-runner in directory $absdir"

test -d $absdir/log && rm -rf $absdir/log
test -d $absdir/cache && rm -rf $absdir/cache

test -h $absdir/etc/adm.d/org.ops4j.pax.logging.cfg && rm -f $absdir/etc/adm.d/org.ops4j.pax.logging.cfg
test -e $absdir/etc/adm.d/org.ops4j.pax.logging.cfg || \
  ln -s /etc/osgi-runner/adm.d.examples/logback/org.ops4j.pax.logging.cfg $absdir/etc/adm.d/org.ops4j.pax.logging.cfg

akfile=$absdir/etc/sshd.d/authorized_keys

if test ! -f $akfile
then
    if test -f $HOME/.ssh/authorized_keys
    then
        echo '***** '"Copying $HOME/.ssh/authorized_keys to $akfile"
        cp $HOME/.ssh/authorized_keys $akfile
    else
        echo '***** '"Filling $akfile using 'ssh-add -L'"
        ssh-add -L >  $akfile
    fi
fi

echo '***** '"Creating $absdir/log"
mkdir -p $absdir/log
echo '***** '"Creating $absdir/cache"
mkdir -p $absdir/cache

exec java -Dosgi.runner.etcPath=/etc/osgi-runner -Dosgi.runner.etcOverridePath=$absdir/etc -Dfile.encoding=utf-8 -Djava.awt.headless=true $DEBUG_OPTS -cp '/usr/share/osgi-runner/lib/*:/usr/share/osgi-runner/drivers/*' org.clazzes.osgi.runner.Main
