#!/bin/bash
#

if [[ $# -lt 2 ]] ; then
	exit 1
fi

mac=$(</sys/class/net/eth0/address)
mac=${mac//:}

device_ip=$3
appliance_ip=$(hostname -I)

MQTT_MSG=$1
MSG_IDENTIFIER=$2

MQTT_DIR=/etc/mosquitto
MQTT_PWD_FILE=$MQTT_DIR/mqtt_pwd
MQTT_UNAME=nyquist

if [ ! -f $MQTT_PWD_FILE ]; then
	MQTT_PWD=NyCtrlPwdDefault2022
else
	MQTT_PWD=$(cat $MQTT_PWD_FILE)
fi

if [[ $MQTT_MSG == "protection_mode" ]] ; then
	#echo "mosquitto_pub -h $MSG_IDENTIFIER -u $MQTT_UNAME -P $MQTT_PWD -t $1 -m $mac --cafile /etc/mosquitto/bogenCA.crt"
	mosquitto_pub -h $MSG_IDENTIFIER -u $MQTT_UNAME -P $MQTT_PWD -t $1 -m $mac --cafile /etc/mosquitto/bogenCA.crt
elif [[ $MQTT_MSG == "checkin" ]] ; then
	#echo "mosquitto_pub -h $MSG_IDENTIFIER -u $MQTT_UNAME -P $MQTT_PWD -t $MQTT_MSG -m $3 --cafile /etc/mosquitto/bogenCA.crt"
	mosquitto_pub -h $MSG_IDENTIFIER -u $MQTT_UNAME -P $MQTT_PWD -t $MQTT_MSG -m $3 --cafile /etc/mosquitto/bogenCA.crt
elif [[ $MQTT_MSG == "ip-address" ]] ; then
	#echo "mosquitto_pub -h $MSG_IDENTIFIER -u $MQTT_UNAME -P $MQTT_PWD -t sm_server -m \"$mac ip-address $appliance_ip\" --cafile /etc/mosquitto/bogenCA.crt"
	mosquitto_pub -h $MSG_IDENTIFIER -u $MQTT_UNAME -P $MQTT_PWD -t sm_server -m "$mac ip-address $appliance_ip" --cafile /etc/mosquitto/bogenCA.crt
elif [[ $MQTT_MSG == "sm_server" ]] ; then
	sm_cmd=$3
	zone=$4
	num_days_left=$5
	#echo "mosquitto_pub -h $MSG_IDENTIFIER -u $MQTT_UNAME -P $MQTT_PWD -t $MQTT_MSG -m \"$mac $sm_cmd $zone $num_days_left\" --cafile /etc/mosquitto/bogenCA.crt"
	mosquitto_pub -h $MSG_IDENTIFIER -u $MQTT_UNAME -P $MQTT_PWD -t $MQTT_MSG -m "$mac $sm_cmd $zone $num_days_left" --cafile /etc/mosquitto/bogenCA.crt
fi
