#!/bin/bash

BINPATH="/usr/bin"
BINARY="crystal"
#RUNFILE=""
FILEOPTS="play"
LIBNOTIFY="true"
LOGDIR="/tmp"


# Colors
RED='\033[0;31m'
LRED="\033[1;31m"
BLUE="\033[0;34m"
LBLUE="\033[1;34m"
GREEN="\033[0;32m"
LGREEN="\033[1;32m"
YELLOW="\033[1;33m"
CYAN="\033[0;36m"
LCYAN="\033[1;36m"
PURPLE="\033[0;35m"
LPURPLE="\033[1;35m"
BWHITE="\e[1m"
NC='\033[0m' # No Color


#####################################



CheckNotify()
{
  if [ "${LIBNOTIFY}" = "true" ];then
    notify-send "$1"
  elif [ "${LIBNOTIFY}" = "false" ];then
    "$1" &> /dev/null
    echo "$(date +"%T"): [INFO]: libnotify support disabled" >> ${LOGDIR}/${LOGFILE}
  else
    echo "[ATTENTION]: Please check the logs: /tmp/${BINARY}.log"
    echo "$(date +"%T"): [WARNING]: LIBNOTIFY setting is invalid" >> ${LOGDIR}/${LOGFILE}
  fi
}

case "$1" in
  start) nohup ${BINPATH}/${BINARY} ${FILEOPTS} &> /dev/null &

  sleep 1

  PID=$(pidof ${BINARY})

  if [ "${PID}" ];then
    CheckNotify "${BINARY} started on PID: ${PID}"
    echo
    printf "${LGREEN}${BINARY} started on PID: ${PID}${NC}\n"
    printf "${LGREEN}Web Server started on localhost:8080${NC}\n"

  else
    CheckNotify "${BINARY} Failed to start!"
    printf "${LRED}${BINARY} process failed to start!${NC}\n"
  fi
  ;;

  stop) killall ${BINARY}
  sleep 1
  if [ ! "${PID}" ];then
    CheckNotify "${BINARY} was terminated"
    echo
    printf "${LRED}${BINARY} was terminated${NC}\n"
  else
    CheckNotify "There was a problem terminating ${BINARY}"
    printf "${LRED}There was a problem terminating ${BINARY}${NC}"
  fi


  ;;

  open) xdg-open "http://localhost:8080" &> /dev/null
  ;;

  status) ps -fC ${BINARY}
  ;;

  *)
    echo """
    Usage: crystald [option]

    [Options]   [Description]

    start       Starts crystal play on port 8080
    stop        Kills process 'crystal'
    open        Opens web browser to localhost:8080
    status      Shows process status

    """
esac
