#!/usr/bin/env bash

#strict mode
set -e

# read helper functions
source "/usr/share/image-launch/functions"

# get the real path of the image-launch installation
BOOTSTRAP_ST="/usr/share/image-launch/bootstrap.st"

# config file can be located by providing it as first argument. The
# directory of the config will also be added as candidate to find
# launch.d dir
if [ -f "$1" ] || [ -d "$1" ] ;
then
   FILE_IN_FIRST_ARG=$1
   # this argument is not needed in image so we skip it
   shift
fi

# check for bash relevant options
CMDLINE_ARGS=""
while [ "$1" != "" ]; do
   case $1 in
      # switch to debug this script. Different then verbose output for
      # start script handling
      --debug )
         DEBUG_SCRIPT=1
         shift
         ;;
      # just copy to rest for pharo to parse
      * )
         CMDLINE_ARGS="$CMDLINE_ARGS $1"
         shift
         ;;
    esac
done
logmsg "CMDLINE_ARGS = " $CMDLINE_ARGS

LOG_OUTPUT='>> $IMAGE.log 2>&1'

# resolve path of the config file and load it
readConfig $FILE_IN_FIRST_ARG

# finally find the pid file
resolvePidFile

echo $$ > $PIDFILE

# IMAGE_LAUNCH_DIR can als be specified in the image-launch.conf. This file
# has been sourced already. If the variable is still empty it isn't
# contained in the config file
if [ -z $IMAGE_LAUNCH_DIR ] ;
then
   if [ -d "$CONFIG_DIR/launch.d" ] ;
   then
      # if we can find a directory named image-launch in the same directory
      # as the image-launch.conf we take it
      IMAGE_LAUNCH_DIR="$CONFIG_DIR/launch.d"
   else
      # no more ideas where to look at. give up!
      echo "could not find directory for image-launch scripts"
      exit 1
   fi
fi
logmsg "IMAGE_LAUNCH_DIR = " $IMAGE_LAUNCH_DIR

if [ ! -f $IMAGE ] ;
then
   if [ -f "$CONFIG_DIR/$IMAGE" ] ;
   then
      IMAGE="$CONFIG_DIR/$IMAGE"
   else
      echo "cannot find image"
      exit 1
   fi
fi

logmsg "IMAGE = " $IMAGE

# finally call the vm with the right image and predefined options
#
# VM_BIN VM_ARGUMENTS IMAGE are configured in the image-launch.conf file
logmsg $VM_BIN $VM_ARGUMENTS $IMAGE $PHARO_ARGS $BOOTSTRAP_ST --imagelaunch-dir=$IMAGE_LAUNCH_DIR $IMAGE_ARGS $CMDLINE_ARGS
if [ "$RUN_USER" == "" ]; then
   eval exec $VM_BIN $VM_ARGUMENTS $IMAGE $PHARO_ARGS $BOOTSTRAP_ST --imagelaunch-dir=$IMAGE_LAUNCH_DIR $IMAGE_ARGS $CMDLINE_ARGS $LOG_OUTPUT
else
   eval exec su $RUN_USER -c "$VM_BIN $VM_ARGUMENTS $IMAGE $PHARO_ARGS $BOOTSTRAP_ST --imagelaunch-dir=$IMAGE_LAUNCH_DIR $IMAGE_ARGS $CMDLINE_ARGS $LOG_OUTPUT"
fi
