#!/usr/bin/env bash
# bin/kitten
# Kitten lifecycle init.d style script
SCRIPT_NAME=`basename $0`
DAEMON_BIN="foreman"
DAEMON=`which $DAEMON_BIN`
DAEMON_RUN_DIR=$PWD/"spec/dummy"
DAEMON_PID_FILE="${SCRIPT_NAME}.run"
DAEMON_LOG_FILE="${SCRIPT_NAME}.log"
DAEMON_CMD="$DAEMON start -f Procfile.static"
PATH=$PATH:".:bin:spec/dummy/bin:$PATH"

# Allow `./kitten [command]`  to function when called within `bin` by
#   returning to the project root directory. The purpose of the `sleep` calls
#   is to allow it to be run from within `bin` (because why not), yet  make it
#   slightly inconvenient so users end up correcting their behavior. Pavlov ftw
if [ `basename $PWD` == "bin" ]; then
  echo "You're in bin/ when you should be executing this from the kitten root directory"
  echo "Step back..."
  sleep 2
  echo "A little more!"
  cd ../
  sleep 1
  echo "That's better! you're now in `pwd` as you should"
fi

# Do not run unless run from the right place ; check for a known path to be sure
if [ ! -d $DAEMON_RUN_DIR ]; then
  echo "It looks like you are not in the project root or root/bin directory."
  echo "cd to the project root directory and retry."
  exit 1
fi

usage() {
    cat << EOF
USAGE: $SCRIPT_NAME {start [-t]|stop|forcestop|restart|buildstatic|status|log|install|cleanup|test}
EOF
}

cleanup() {
  echo "Are you really sure you want to cleanup ? That cannot be undone. [yes|No] "
 local SURE
  read SURE
  if [ "$SURE" = "yes" ]; then
    stop
    cd -
    bash ./bin/cleanup
  fi
  echo "Cleanup done"
}

status(){
  echo Getting $SCRIPT_NAME status
  cd $DAEMON_RUN_DIR
  if [ -f  $DAEMON_PID_FILE ];then
    RUN=`head -n1 $DAEMON_PID_FILE`
    kill -0 $RUN >/dev/null 2>&1
    result=$?
    if [ ${result} -eq 0 ];then
      echo "$SCRIPT_NAME is running with PID ${RUN}."
    else
      echo "$SCRIPT_NAME is not running but pid file subsists."
      echo "Try :"
      echo "    ./bin/$SCRIPT_NAME forcestop "
    fi
  else
    echo "$SCRIPT_NAME is not running ($DAEMON_RUN_DIR/$DAEMON_PID_FILE not found)"
  fi
}

test(){
  if [ ! -d node_modules ];then
    echo $SCRIPT_NAME has missing files
    echo Did you run
    echo "    ./bin/$SCRIPT_NAME install"
    exit 1
  fi
  set -e
  FILES=${2:-assets/javascripts/**/*.test.js}
  yarn test -- "$FILES"
}

install(){
  if [ -d "nodes_modules" ]; then
    echo There seems to be a previous install of $SCRIPT_NAME
    cleanup
  fi
  bash ./bin/install
}

start(){
  if [ ! -d node_modules ];then
    echo $SCRIPT_NAME has missing files
    echo Did you run
    echo "    ./bin/$SCRIPT_NAME install"
    exit 1
  fi

  cd $DAEMON_RUN_DIR

  chmod +x bin/rails

  if [ ! -f  $DAEMON_PID_FILE ];then
    echo "Starting $SCRIPT_NAME"
    $DAEMON_CMD 1>$DAEMON_LOG_FILE 2>&1 &
		echo $! > $DAEMON_PID_FILE 2>&1 &
    case "$1" in
      "-t")
        tail -n 20 -f $DAEMON_LOG_FILE
      ;;
    esac
  else
    echo "Error when starting ${SCRIPT_NAME}: pid file $DAEMON_RUN_DIR/$DAEMON_PID_FILE found"
		exit 1
  fi
}

forcestop(){
  cd $DAEMON_RUN_DIR
	echo Forcing $SCRIPT_NAME stop
  for PID in `ps ax | grep 'spec/dummy' | grep -v grep| awk ' { print $1;}'`; do
    kill -9 $PID 1>/dev/null 2>&1
    if [ $? == 0 ];then
      echo PID $PID killed
    else
      echo Could not kill process $PID
    fi
  done
	rm -f $DAEMON_PID_FILE 1>/dev/null 2>&1
  if [ $? == 0 ];then
	  echo lockfile removed
  else
    echo Could not remove lockfile
  fi
}

is_running() {
  [ -f $DAEMON_PID_FILE ] && ps `cat $DAEMON_PID_FILE` > /dev/null 2>&1
}

stop(){
  cd $DAEMON_RUN_DIR
  if [ -f $DAEMON_PID_FILE ];then
    PID=`cat $DAEMON_PID_FILE`
    ps $PID >/dev/null 2>&1
    if [ $? == 0 ];then
      echo $SCRIPT_NAME is running with pid $PID
      echo Killing process $PID
      kill $PID 1>/dev/null 2>&1
      if [ $? == 0 ];then
        echo $SCRIPT_NAME killed
      else
        echo Could not kill $SCRIPT_NAME, try forcestop
      fi
    else
      echo $SCRIPT_NAME not running, removing $DAEMON_RUN_DIR/$DAEMON_PID_FILE
    fi
    rm -f $DAEMON_PID_FILE 1>/dev/null 2>&1
    if [ $? == 0 ];then
      echo Lockfile $DAEMON_RUN_DIR/$DAEMON_PID_FILE removed
    else
      echo Could not remove lock file, try forcestop
    fi
  else
    echo Lockfile $DAEMON_RUN_DIR/$DAEMON_PID_FILE not found
  fi
}

is_installed(){
 [ -d node_modules ]
}

case "$1" in
  start|stop|forcestop|cleanup|install|usage)
    ${1}
    ;;
  test)
    test $1
    ;;
  restart)
    stop
    start
    ;;
  status)
    status
    ;;
  buildstatic)
    stop
    cd -
    start
		echo Waiting for $SCRIPT_NAME to be fully launched
    sleep 50
    echo Launching crawler
    /usr/bin/perl $DAEMON_RUN_DIR/bin/fashionista.pl
    if [ ! -d "../../build" ]; then
      echo Something went wrong while building static $SCRIPT_NAME
      exit 1
    fi
    cd -
    stop
    ;;
  log)
    cd $DAEMON_RUN_DIR && tail -f -n 30 $DAEMON_LOG_FILE
    ;;
  *)
    usage
    exit 1
    ;;
esac

exit 0
