#!/bin/bash
# --- Settings ---

SLEEP_TIME=60

# FRITZ!Box Domoticz
DOMO_IP="127.0.0.1"
DOMO_PORT="80"
DOMO_FRITZ_VALUES=""$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/saved/thermostats"

# Levels: 0: Off, 10: Comfort, 20: Saving, 30: Manual
DOMO_SELECTOR_RADIATOR=(0 10 20 30)

# Name of thermostats in FRITZ!Box
ROOMS=("Heizung Wohnzimmer" "Heizung Kinderzimmer" "Heizung Badezimmer" "Heizung Schlafzimmer")

# IDX in domoticz
IDX_SETPOINT=("1" "4" "7" "10")
IDX_MEASURED=("2" "5" "8" "11")
IDX_SELECTOR=("3" "6" "9" "12")

while true
do
	echo
        echo "!---------------------------------------------------> Start while <------------------------------------------------------!"
        echo
	echo "!-----------------------------------> Preparing directory..."
	# Prepare directory and files
	if [ ! -d "$DOMO_FRITZ_VALUES" ]; then
		mkdir $DOMO_FRITZ_VALUES
	fi
	echo "!-----------------------------------> Done!"
	echo
	echo "!-----------------------------------> Getting data from FRITZ!Box with fritzctl"
	# Get data from FRITZ!Box api - fritzctl required
	INPUT=$(fritzctl list thermostats)
	echo "$INPUT"
	echo "!-----------------------------------> Done!"
	echo
	echo "!-----------------------------------> Starting update rooms..."
	# The skript
	for ((room=0;room<${#ROOMS[@]};room++)); do

		echo
                echo "!---------------------------------------------------> "${ROOMS[room]}" <------------------------------------------------------!"
                echo
		echo "!-----------------------------------> Preparing text files..."
		# Prepare text files to store values for detect changes
		if [ ! -d ""$DOMO_FRITZ_VALUES"/"$(echo "${ROOMS[room]}" | tr -d ' ')"" ]; then
			touch ""$DOMO_FRITZ_VALUES"/"$(echo "${ROOMS[room]}" | tr -d ' ')""
		fi
		echo "!-----------------------------------> Done!"
		echo
		echo "!-----------------------------------> Preparing parameters..."
		# Get data from input (fritzctl) and domoticz
		SETPOINT=$(curl -s -i -H "Accept: application/json" "http://$DOMO_IP:$DOMO_PORT/json.htm?type=devices&rid=${IDX_SETPOINT[room]}" | grep "\"SetPoint\" :.*" | cut -d: -f 2 | tr -d ' ' | tr -d '"' | tr -d ",")
		echo "!-----------------------------------> Setpoint: $SETPOINT"
		PRESENT=$(echo "$INPUT" | grep "${ROOMS[room]}" | cut -d '|' -f 4 | tr -d ' ')
		echo "!-----------------------------------> Present: $PRESENT"
		BOXLOCK=$(echo "$INPUT" | grep "${ROOMS[room]}" | cut -d '|' -f 5 | cut -d '/' -f 1 | tr -d ' ')
		echo "!-----------------------------------> Boxlock: $BOXLOCK"
		MEASURED=$(echo "$INPUT" | grep "${ROOMS[room]}" | cut -d '|' -f 6 | tr -d '°C' | tr -d ' ')
		echo "!-----------------------------------> Measured: $MEASURED"
		WANT=$(echo "$INPUT" | grep "${ROOMS[room]}" | cut -d '|' -f 8 | tr -d '°C' | tr -d ' ')
		echo "!-----------------------------------> Want: $WANT"
		SAVING=$(echo "$INPUT" | grep "${ROOMS[room]}" | cut -d '|' -f 9 | tr -d '°C' | tr -d ' ')
		echo "!-----------------------------------> Saving: $SAVING"
		COMFORT=$(echo "$INPUT" | grep "${ROOMS[room]}" | cut -d '|' -f 10 | tr -d '°C' | tr -d ' ')
		echo "!-----------------------------------> Comfort: $COMFORT"
		BATTERY=$(echo "$INPUT" | grep "${ROOMS[room]}" | cut -d '|' -f 13 | tr -d ' ')
		if [ "$BATTERY" == "✔" ]; then
			BATTERY=100
		else
			BATTERY=0
		fi
		echo "!-----------------------------------> Battery: $BATTERY"
		SAVED=$(echo $(cat ""$DOMO_FRITZ_VALUES"/"$(echo "${ROOMS[room]}" | tr -d ' ')"") | tr -d ' ')
		echo "!-----------------------------------> Saved: $SAVED"
		SELECTOR=$(curl -s -i -H "Accept: application/json" "http://$DOMO_IP:$DOMO_PORT/json.htm?type=devices&rid=${IDX_SELECTOR[room]}" | grep "\"Level\" :.*" | cut -d: -f 2 | tr -d ' ' | tr -d '"' | tr -d ",")
                echo "!-----------------------------------> Selector: $SELECTOR"
		echo "!-----------------------------------> Done!"
		echo
		echo "!-----------------------------------> Checking present..."
		if [ "$PRESENT" == "✘" ]; then
			echo "echo !-----------------------------------> Not present! Skip room!"
			continue
		fi
		echo "!-----------------------------------> Yes!"
		echo
		echo "!-----------------------------------> Writing measured temperature to domoticz..."
		# Load data in domoticz
		curl -s -i -H "Accept: application/json" "http://$DOMO_IP:$DOMO_PORT/json.htm?type=command&param=udevice&idx=${IDX_MEASURED[room]}&nvalue=0&svalue=$MEASURED&battery=$BATTERY"
		echo "!-----------------------------------> Done!"
		echo
		echo "!-----------------------------------> Reading selector switches from domoticz and possibly write setpoint new..."
		echo "!-----------------------------------> Setpoint(old): $SETPOINT"
		# Initiate new domoticz
		if [[ -z "$SETPOINT" ]]; then
			SETPOINT=$WANT
		# Setpoints from selector
		elif [[ "$SELECTOR" -eq "${DOMO_SELECTOR_RADIATOR[0]}" ]] && ! [[ "$WANT" =~ ^[A-Z]+$ ]]; then
			SETPOINT="0"
		elif [[ "$SELECTOR" -eq "${DOMO_SELECTOR_RADIATOR[1]}" ]] && ( [[ "$WANT" =~ ^[A-Z]+$ ]] || ( [[ $(bc <<< "$WANT != $COMFORT") -eq 1 ]] && [[ $(bc <<< "$SAVED == $SETPOINT") -eq 1 ]] )); then
			SETPOINT="$COMFORT"
		elif [[ "$SELECTOR" -eq "${DOMO_SELECTOR_RADIATOR[2]}" ]] && ( [[ "$WANT" =~ ^[A-Z]+$ ]] || ( [[ $(bc <<< "$WANT != $SAVING") -eq 1 ]] && [[ $(bc <<< "$SAVED == $SETPOINT") -eq 1 ]] )); then
			SETPOINT="$SAVING"
		fi
		echo "!-----------------------------------> Setpoint(new): $SETPOINT"
		echo "!-----------------------------------> Done!"
		echo
		echo "!-----------------------------------> Writing setpoint with fritzctl or update setpoints..."
		# Setpoints
		if [[ "$BOXLOCK" == "✘" ]] && ( ( [[ "$SAVED" =~ ^[A-Z]+$ ]] && [[ "$SETPOINT" =~ ^[0]+\.?[0]*$ ]] ) || [[ $(bc <<< "$SAVED != $SETPOINT") -eq 1 ]] ) ; then
			echo "!-----------------------------------> Writing setpoints with fritzctl..."
			if [[ "$SETPOINT" =~ ^[0]+\.?[0]*$ ]]; then
				fritzctl temperature OFF "${ROOMS[room]}"
			elif [[ "$SETPOINT" =~ ^[0-9]+\.?[0-9]*$ ]]; then
				fritzctl temperature "$SETPOINT" "${ROOMS[room]}"
			fi
			echo "!-----------------------------------> Done!"
		else
			echo "!-----------------------------------> Setpoint(old): $SETPOINT"
			if [[ "$WANT" =~ OFF ]]; then
                                SETPOINT=0.0
                        else
                                SETPOINT=$WANT
                        fi
			echo "!-----------------------------------> Setpoint(new): $SETPOINT"
			echo "!-----------------------------------> Done!"
		fi
		echo
		echo "!-----------------------------------> Writing setpoint to domoticz..."
		curl -s -i -H "Accept: application/json" "http://$DOMO_IP:$DOMO_PORT/json.htm?type=command&param=udevice&idx=${IDX_SETPOINT[room]}&nvalue=0&svalue=$SETPOINT"
		echo "$SETPOINT" | dd of=""$DOMO_FRITZ_VALUES"/"$(echo "${ROOMS[room]}" | tr -d ' ')""
		echo "!-----------------------------------> Done!"
		echo
		echo "!-----------------------------------> Updating selector..."
		# Selector Switch State Levels: 0: Off, 10: Comfort, 20: Saving, 30: Manual
		if [[ "$SETPOINT" =~ ^[0]+\.?[0]*$ ]]; then
			curl -s -i -H "Accept: application/json" "http://$DOMO_IP:$DOMO_PORT/json.htm?type=command&param=switchlight&idx=${IDX_SELECTOR[room]}&switchcmd=Set%20Level&level=${DOMO_SELECTOR_RADIATOR[0]}"
		elif [[ "$SETPOINT" =~ ^[0-9]+\.?[0-9]*$ ]]; then
			if [[ $(bc <<< "$SETPOINT == $COMFORT") -eq 1 ]]; then
				curl -s -i -H "Accept: application/json" "http://$DOMO_IP:$DOMO_PORT/json.htm?type=command&param=switchlight&idx=${IDX_SELECTOR[room]}&switchcmd=Set%20Level&level=${DOMO_SELECTOR_RADIATOR[1]}"
			elif [[ $(bc <<< "$SETPOINT == $SAVING") -eq 1 ]]; then
				curl -s -i -H "Accept: application/json" "http://$DOMO_IP:$DOMO_PORT/json.htm?type=command&param=switchlight&idx=${IDX_SELECTOR[room]}&switchcmd=Set%20Level&level=${DOMO_SELECTOR_RADIATOR[2]}"
			else
				curl -s -i -H "Accept: application/json" "http://$DOMO_IP:$DOMO_PORT/json.htm?type=command&param=switchlight&idx=${IDX_SELECTOR[room]}&switchcmd=Set%20Level&level=${DOMO_SELECTOR_RADIATOR[3]}"
			fi
		fi
		echo "!-----------------------------------> Done!"
		echo
	done
	echo "!-----------------------------------> Rooms done!"
	echo "!-----------------------------------> Going to sleep for $SLEEP_TIME s"
	echo
	sleep $SLEEP_TIME

done
