#!/bin/bash
set -e

worker=$(basename $0)
script_dir=$(dirname $(readlink -f $0))
src_dir=$(dirname $(dirname $(dirname $(dirname $script_dir))))

echo "SOURCE DIR = $src_dir, script_dir = $script_dir"

rc_dir=$src_dir/.dev-tools.rc
export IGNORE_FILE=$rc_dir/ignored.txt
if [[ "$worker" =~ deploy ]]; then
  env_file=$rc_dir/deploy.sh
else
  env_file=$rc_dir/devel.sh
fi

if [ -f $env_file ]; then
  source $env_file
else
  echo Warning: could not find resources file. Will use default settings
fi


if [ "$UI_BUILD_PATH" = "" ]; then
  export UI_BUILD_PATH=$HOME/build/ui
fi
mkdir -p "$UI_BUILD_PATH"

if [ "$UI_SRC_PATH" = "" ]; then
  export UI_SRC_PATH=$src_dir
fi

proc_tag=$(echo $UI_SRC_PATH/$worker | sed -e "s/\//-/g" | sed -E "s/^\-|\-$|\.sh//g" )
if [ "$TMPDIR" = "" ]; then
  pidfile=/tmp/${proc_tag}.pid
  pidcheck=/tmp/${proc_tag}.check
else
  pidfile=$TMPDIR${proc_tag}.pid
  pidcheck=$TMPDIR${proc_tag}.check
fi

echo Using pidfile=$pidfile

if [ -f $pidfile ]; then
  pid=$(cat $pidfile)
  ps -p $pid | grep $pid | sed -E "s/^ *//" | sed -E "s/ .*$//" > $pidcheck
  plist=$(cat $pidcheck)
  echo "PLIST=$plist // $pid"
  if [ "$plist" = "$pid" ]; then
    echo there is already a watcher with $pid
    exit 1
  fi 
fi 

if [ -f $pidfile ]; then
  rm "$pidfile"
fi

echo $$ > $pidfile

echo "Start watching from $UI_SRC_PATH"
if [ -z $UI_BUILD_MODE ]; then
  export UI_BUILD_MODE=development
fi

if [ "$UI_BUILD_MODE" = "development" ]; then
  watch="--watch"
fi
  env_file=$rc_dir/deploy.sh

if [ -d $rc_dir/prepare ]; then
  for l in $(ls); do
    if [ -x $l ]; then
      $l
    fi
  done
fi

if [ "$BUILD_SEEDS" != "no" ]; then
  if [ "$SEEDS_ROOTS" != "" ]; then
    $script_dir/../seeds/index.js --from=$UI_SRC_PATH --libs=$SEEDS_ROOTS
  else
    $script_dir/../seeds/index.js --from=$UI_SRC_PATH 
  fi
fi

webpack --config webpack.js --mode=$UI_BUILD_MODE --progress $watch
