#!/usr/bin/env bash

# Dependencies:
# - inotify-tools

MY_PIDFILE=tmp/pids/my.pid
PUMA_PIDFILE=tmp/pids/puma.pid

case $1 in
  "start")
    if [ -e $MY_PIDFILE ]
    then
      echo "PID file $MY_PIDFILE found, please run \"rails_server stop\" first"
      exit 1
    fi

    if [ -e $PUMA_PIDFILE ]
    then
      echo "PID file $PUMA_PIDFILE found, please run \"rails_server stop\" first"
      exit 1
    fi

    start_server () {
      bundle exec puma config.ru -d --pidfile $PUMA_PIDFILE --redirect-stdout log/puma.log --redirect-stderr log/puma.log
    }

    start_server

    nohup inotifywait -m tmp/restart.txt -e attrib -q | while read event; do
      test -e "$PUMA_PIDFILE" && pumactl --pidfile $PUMA_PIDFILE status
      if [ $? -ne 0  ]
      then
        start_server
      else
        bundle exec pumactl --pidfile $PUMA_PIDFILE stop
        start_server
      fi
    done > log/puma.log 2>&1&

    echo $! > $MY_PIDFILE
    ;;
  "stop")
    test -e $MY_PIDFILE && ps --pid $(cat $MY_PIDFILE) &>/dev/null
    if [ $? -eq 0 ]
    then
      kill -9 $(cat $MY_PIDFILE)
      echo "Turned off monitor"
    else
      echo "Monitor is not running"
    fi
    rm -f $MY_PIDFILE

    test -e $PUMA_PIDFILE && ps --pid $(cat $PUMA_PIDFILE) &>/dev/null
    if [ $? -eq 0 ]
    then
      bundle exec pumactl --pidfile $PUMA_PIDFILE stop
      echo "Turned off Puma"
    else
      echo "Puma is not running"
    fi
    rm -f $PUMA_PIDFILE
    ;;
  *)
    echo "Usage: rails_server start|stop"
    ;;
esac