#!/bin/sh


# Configuration  parameters:
EAGLE_I_DB_DIR="db"
EAGLE_I_DB_NAME="eagle-i-users.derby"
SLASH_LIB="/lib"

X_HOME=`dirname $0`

if [ -n "$1" ]; then
   REPOSITORY_HOME="$1"
fi

if [ -z "$REPOSITORY_HOME" ]; then
   echo    "!* ERROR:"
   echo    " * REPOSITORY_HOME was not provide/is not set."
   echo    " * usage: $0 <path to repository home> <path to backup directory>"
   echo    " * or set environment variable REPOSITORY_HOME"
   echo -n " * or enter REPOSITORY HOME now:"
   read REPOSITORY_HOME
fi
if [ -d "${REPOSITORY_HOME}" ]
then
    echo "Using \"${REPOSITORY_HOME}\" as repository home"
else
    echo "!* Error, \"${REPOSITORY_HOME}\" does not exist, exiting..."
    exit 1
fi


if [ -n "$2" ]; then
   BACKUP_DIR="$2"
fi
if [ -z "$BACKUP_DIR" ]; then
   echo    "!* ERROR:"
   echo    " * The backup directory was not provide/is not set."
   echo    " * usage: $0 <path to repository home>"
   echo    " * or set environment variable REPOSITORY_HOME"
   echo -n " * or enter the backup directory now:"
   read BACKUP_DIR
fi

if [ -z ${DERBY_HOME} ]; then
   echo "`basename $0` will use the derby distribution provided by the eagle-i repository!"
   DERBY_HOME=${X_HOME}
   DERBY_JARS=`echo ${DERBY_HOME}/lib/derby*.jar | tr ' ' :`
   echo ${DERBY_JARS}
else
   if [ -d "${DERBY_HOME}" ]
   then
      echo "!* WARNING:"
      echo " * `basename $0` detected Apache Derby at:"
      echo " * \"${DERBY_HOME}\" ."
      echo " * The DERBY_HOME environment parameter is"
      echo " * set. `basename $0` will use the derby"
      echo " * libraries setup on this host. "
      DERBY_JARS="${DERBY_HOME}${SLASH_LIB}/derby.jar:${DERBY_HOME}${SLASH_LIB}/derbytools.jar"
   else
      echo "!* Error, \"${DERBY_HOME}\" does not exist, exiting..."
      exit 2
   fi
fi

DASHD_URL="-Dij.database=jdbc:derby:${REPOSITORY_HOME}/${EAGLE_I_DB_DIR}/${EAGLE_I_DB_NAME};createFrom=${BACKUP_DIR}/${EAGLE_I_DB_NAME}"

if [ -d "${BACKUP_DIR}/${EAGLE_I_DB_NAME}" ]; then
    echo "Restoring ${REPOSITORY_HOME}/${EAGLE_I_DB_DIR} from backup ${BACKUP_DIR}"
    echo "Following users have been restored:"
echo "select Username from Users" | \
    java -cp "${DERBY_JARS}"  \
         "${DASHD_URL}" \
         org.apache.derby.tools.ij #&>/dev/null
    echo "...done."
    exit 0
fi

echo "*** ERROR: ${BACKUP_DIR} does not exist or is not a valid backup directory!";
exit 1
