#!/bin/sh

printf "Content-Type: application/json\n\n"

CUSTOMER_ID="$(jq .cid -r /home/hubclient/files/config.json)"
DEVICE_ID="$(jq .tid -r /home/hubclient/files/config.json)"

if [ "$REQUEST_METHOD" = "GET" ]
then
   printf "{\"cid\":\"%s\",\"tid\":\"%s\"}\n" "${CUSTOMER_ID}" "${DEVICE_ID}"
elif  [ "$REQUEST_METHOD" = "POST" ]
then
   ID=$(jq .)

   NEW_CUSTOMER_ID="$(printf "%s" "$ID" | jq .cid -r)"
   NEW_DEVICE_ID="$(printf "%s" "$ID" | jq .tid -r)"

   if [  ! "$NEW_CUSTOMER_ID" = "" ] && [ ! "$NEW_DEVICE_ID" = "" ]
   then
      if [ ! "$NEW_CUSTOMER_ID" = "$CUSTOMER_ID" ] || [ ! "$NEW_DEVICE_ID" = "$DEVICE_ID" ]
      then
         UPDATE="$(printf "{\"params\":{\"cid\":\"%s\",\"tid\":\"%s\"}}" "$NEW_CUSTOMER_ID" "$NEW_DEVICE_ID")"
         curl http://localhost/cgi-bin/hubclient/abortcurrentplan >/dev/null
         curl -d "$UPDATE" http://localhost/cgi-bin/hubclient/parameters
         rm -rf /home/hubclient/files/params.json
         rm -rf /home/hubclient/plan/
         sync
         killall hub_daemon_starter.sh
         start-stop-daemon -K -q -x "/home/hubclient/bin/hubclientdaemon"
         /home/hubclient/bin/hub -x
         start-stop-daemon -S -q -b -x "/home/hubclient/bin/hub_daemon_starter.sh"
      else
         #the same value was entered
         printf "{}"
      fi
   else
      printf "{\"errorCode\":1,\"errorMessage\":\"Empty value entered.\"}"
   fi
else
   printf "{\"errorCode\":1,\"errorMessage\":\"Unsupported method %s.\"}" "$REQUEST_METHOD"
fi