#!/usr/bin/env bish-bosh

mkdir -p /var/run/bish-bosh/client
mkdir -p /var/run/bish-bosh/session
mkdir -p /var/run/bish-bosh/lock

bishbosh_clientPath=/var/run/bish-bosh/client
bishbosh_sessionPath=/var/run/bish-bosh/session
bishbosh_lockPath=/var/run/bish-bosh/lock

ROOT=/www
CONFIG=$ROOT/config
SCRIPT=$ROOT/script

source $CONFIG/ap.conf
source $CONFIG/api.conf
source $CONFIG/mqtt.conf

source $SCRIPT/utils/date.sh
source $SCRIPT/utils/misc.sh

DEVICE_ID="$bishbosh_connect_username"

# subscribe topic
listenTopic="listeners/$DEVICE_ID"

# topics
statusTopic="statuses/$DEVICE_ID"
reportTopic="stats/update/$DEVICE_ID"
updateSessionTopic="sessions/update/$DEVICE_ID"
commandResponseTopic="command/response/$DEVICE_ID"

# config
now=`nowAsUnixEpoch`
lastReport=$((now - 10))

bishbosh_clientId="$DEVICE_ID"
bishbosh_connect_cleanSession=1
bishbosh_connect_willTopic="$statusTopic"
bishbosh_connect_willMessage="offline"
bishbosh_connect_willQoS=1
bishbosh_connect_willRetain=1

bishbosh_connect_keepAlive=5

bishbosh_connection_handler_PINGRESP() {
  echo pong >&2
}

bishbosh_connection_handler_CONNACK() {
  # send online message
  bishbosh_publishText 1 "$statusTopic" yes "online"

  # Listen server commands
  bishbosh_subscribe "$listenTopic" 1
}

bishbosh_connection_handler_PUBLISH() {
  local message=`mktemp`
  tr -d %'\r' < "$messageFilePath" > "$message"
  rm -rf "$topicNameFilePath"
  rm -rf "$messageFilePath";

  local topic="`cat $message | sed -n '1p'`"
  local data="`cat $message | sed -n '2p'`"
  rm -rf "$message"
  echo "command $topic $data" >&2
  local response=`$SCRIPT/utils/command.sh "$topic" "$data"`
  [ -z "$response" ] || bishbosh_publishText 0 "$commandResponseTopic" no "$response"
}

bishbosh_connection_handler_noControlPacketsRead() {
  now=`nowAsUnixEpoch`
  touch /tmp/now.job

  # update session & stats
  diff=$((now - lastReport))
  if [ "$diff" -gt 15 ] ; then
    updateData="`$SCRIPT/report/stats.sh`"
    [ ! -z "$updateData" ] && bishbosh_publishText 0 "$reportTopic" no "$updateData"

    updateData="`$SCRIPT/report/session.sh`"
    [ ! -z "$updateData" ] && bishbosh_publishText 0 "$updateSessionTopic" no "$updateData"

    lastReport="$now"
  fi
}

onExit() {
  echo "exit" >&2
  bishbosh_publishText 1 "$statusTopic" yes "offline"
}

# Catch onexit
trap onExit INT HUP TERM ABRT QUIT
