#!/bin/sh

SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
cd "$SCRIPT_DIR/new-server"

ERRMSG="Installation failed."
if test -e ../srvctrl; then
  ERRMSG="Existing Management Console installation was not modified."
fi

CHECK_JS_FILE=./server/check.js
if test ! -e $CHECK_JS_FILE; then

  ls server/lib | grep -v service.node | awk -F . '{print "require(\"./lib/" $1 "\");"}' > $CHECK_JS_FILE

  if test ! -e $CHECK_JS_FILE; then
    echo $CHECK_JS_FILE is not writable, ensure you have enough permissions to overwrite the new Management Console.
    exit 2
  fi

  if test -z $CHECK_JS_FILE; then
    echo Failed to update $CHECK_JS_FILE, please contact support.
    echo $ERRMSG
    exit 3
  fi

  echo 'console.log("good");' >> $CHECK_JS_FILE

  echo Created $CHECK_JS_FILE
  cat $CHECK_JS_FILE
fi


echo -n "Checking prerequisites... "
if ./nodejs/bin/node $CHECK_JS_FILE | grep -q good; then
  echo "[OK]"
  echo -n "Checking permissions... "

  WRITABLE=no
  if find .. -not -path "../new-server*" -and -not -path "../var*" -print0 | xargs -0 -n1 -- test -w ; then
    WRITABLE=yes
  fi

  RUNNING=yes
  if find .. -not -path "../new-server*" -and -type f -and -executable -print0 | xargs -0 -n1 -- sh -c 'echo -n "" >> $1' -- ; then
    RUNNING=no
  fi

  if test $WRITABLE = no ; then
    echo Failed to modify existing installation.
    echo Please ensure you have enough permissions to write new files and retry.
    echo $ERRMSG
    exit 4
  fi

  if test $RUNNING = yes ; then
    echo Failed to modify existing running installation.
    echo Please stop Management Console and Agent.
    echo $ERRMSG
    exit 5
  fi

  echo "[OK]"
  echo Installing...

  OLD_SRVCTRL=../srvctrl
  NEW_SRVCTRL=./srvctrl

  if test -e $OLD_SRVCTRL; then

    NODE_LINE=`grep -e '^\s*node\s' $OLD_SRVCTRL`

    sh -c 'for arg in "$@"; do (echo $arg | grep -qe "^-") || exit 0; echo $arg; done' $NODE_LINE | \
      ./nodejs/bin/node ./server/migrateSrvctrl.js $NEW_SRVCTRL $OLD_SRVCTRL > $NEW_SRVCTRL.tmp

    if test ! -s $NEW_SRVCTRL.tmp; then
      echo Failed to write new srvctrl file, please ensure enough disk space and permissions are available and retry
      echo $ERRMSG
      exit 8
    fi

    echo "Updated srvctrl:"
    cat $NEW_SRVCTRL.tmp
    if cp -dv $NEW_SRVCTRL.tmp $NEW_SRVCTRL; then
      rm $NEW_SRVCTRL.tmp
    else
      echo Failed to copy new srvctrl file, please ensure enough disk space and permissions are available and retry
      echo $ERRMSG
      exit 9
    fi
  fi

  # copy to preserve attributes
  cd ..
  if cp -dRv new-server/* ./; then
    rm -rf new-server
    echo Done
    exit 0
  fi

  echo Failed to write new Management Console, please contact support.
  exit 6

fi

echo New version of the Management Console failed to start.
echo Please resolve errors above and retry.
echo $ERRMSG
exit 7

