#!/bin/bash
set -e

trap appStop SIGINT SIGTERM

appStart () {
  # start supervisord
  /usr/bin/supervisord -c /etc/supervisor/supervisord.conf

  BURPUI_CONFIG=${BURPUI_CONFIG:-/etc/burp/burpui.cfg}
  BURPUI_CLIENT_NAME=${BURPUI_CLIENT_NAME:-bui}
  BURP_CLIENT_CONFIG=${BURP_CLIENT_CONFIG:-/tmp/burp.conf}
  BURP_SERVER_CONFIG=${BURP_SERVER_CONFIG:-/etc/burp/burp-server.conf}
  BURP_SERVER_ADDR=${BURP_SERVER_ADDR:-auto}
  REDIS_SERVER=${REDIS_SERVER:-redis:6379}
  DATABASE_URL=${DATABASE_URL:-sqlite:////var/lib/burpui/store.db}

  [ "$BURP_SERVER_ADDR" == "auto" ] && {
    BURP_SERVER_ADDR=$(ip route sh | grep default | awk '{print $3;}')
  }

  [ -e "$BURPUI_CONFIG" ] || {
    cp /burp-ui/share/burpui/etc/burpui.sample.cfg $BURPUI_CONFIG
    chown burpui: $BURPUI_CONFIG
  }

  # wait for redis to be up
  sleep 12

  LOGFILE=$(mktemp)
  bui-manage -c $BURPUI_CONFIG setup_burp -b $BURP_CLIENT_CONFIG \
    -s $BURP_SERVER_CONFIG -h $BURP_SERVER_ADDR -c $BURPUI_CLIENT_NAME \
    -r $REDIS_SERVER -d $DATABASE_URL 2>&1 | tee $LOGFILE

  CELERY="True"
  grep -q "Unable to contact the redis server" $LOGFILE && CELERY=""
  rm $LOGFILE

  [ "$DATABASE_URL" != "none" ] && {
    su -l burpui -c "/usr/local/bin/bui-manage -c $BURPUI_CONFIG db upgrade"
  }

  perl -i -pe "s#\@BURPUI_CONFIG\@#$BURPUI_CONFIG#" /etc/gunicorn.d/burp-ui

  echo "Starting crond..."
  supervisorctl start cron >/dev/null

  echo "Starting burp..."
  supervisorctl start burp >/dev/null

  [ -n "$CELERY" ] && {
    echo "Starting bui-celery..."
    supervisorctl start bui-celery >/dev/null
  }

  echo "Starting gunicorn..."
  /etc/init.d/gunicorn restart >/dev/null

  # watch the access logs
  tail -F /var/log/gunicorn/burp-ui_info.log
}

appStop() {
  echo ""
  echo "Stopping gunicorn..."
  /etc/init.d/gunicorn stop >/dev/null
  echo "Stopping burp..."
  supervisorctl stop burp >/dev/null
  echo "Stopping crond..."
  supervisorctl stop cron >/dev/null
  echo "Stopping supervisord..."
  kill -15 $(cat /var/run/supervisord.pid)
  exit
}

appHelp () {
  echo "Available options:"
  echo " app:start          - Starts the gitlab server (default)"
  echo " app:help           - Displays the help"
  echo " [command]          - Execute the specified linux command eg. bash."
}

case "$1" in
  app:start)
    appStart
    ;;
  *)
    if [ -x $1 ]; then
      $1
    else
      prog=$(which $1)
      if [ -n "${prog}" ] ; then
        shift 1
        $prog $@
      else
        appHelp
      fi
    fi
    ;;
esac

exit 0
