#!/bin/bash

GITBUCKETPATH="/home/mollusk/.gitbucket"
WARFILE="gitbucket.war"
LIBNOTIFY="true"
LOGDIR="/tmp"
LOGFILE="gitbucket.log"

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/gitbucket.log"
    echo "$(date +"%T"): [WARNING]: LIBNOTIFY setting is invalid" >> ${LOGDIR}/${LOGFILE}
  fi
}

case "$1" in
  start) nohup java -jar ${GITBUCKETPATH}/${WARFILE} &> /dev/null &

  sleep 1

  PID=$(pidof java)

  if [ "${PID}" ];then
    CheckNotify "Gitbucket started on PID: ${PID}"
    echo "Gitbucket started on PID: ${PID}"
  else
    CheckNotify "Gitbucket Failed to start!"
    echo "Gitbucket process failed to start!"
  fi
  ;;

  stop) killall java
  sleep 1
  if [ ! "${PID}" ];then
    CheckNotify "Gitbucket was terminated"
    echo "Gitbucket was terminated"
  else
    CheckNotify "There was a problem terminating Gitbucket"
    echo "There was a problem terminating Gitbucket"
  fi


  ;;

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

  status) ps -fC java
  ;;
esac
