#!/bin/bash

# Retrieve configuration values
HOSTNAME=$(hostname)
Gateway_EUI=$(uci -q get gateway.general.GWID)

# Retrieve system information
Owner=$(uci -q get remote_management.@general[0].owner)
if [ -z "$Owner" ]; then
    Owner="Dragino"
fi

BROKER="lns1.thingseye.io"
SUB_TOPIC="dragino/gateway/down/$HOSTNAME"
PUB_TOPIC="dragino/gateway/status/$HOSTNAME"
PORT=8883
CAFILE='/usr/local/dragino/monitor/certificates/ca.pem' # Certificate path
MAC=$(dragino-sid |grep MACA|awk '{print $2}')

# Define acknowledgment messages
ack_data="{\"Owner\":\"$Owner\",\"Hostname\":\"$HOSTNAME\",\"Gateway_EUI\":\"$Gateway_EUI\",\"status\":\"ACK\"}"
ack_logging="{\"Owner\":\"$Owner\",\"Hostname\":\"$HOSTNAME\",\"Gateway_EUI\":\"$Gateway_EUI\",\"status\":\"Log_is_being_recorded.\"}"
ack_log="{\"Owner\":\"$Owner\",\"Hostname\":\"$HOSTNAME\",\"Gateway_EUI\":\"$Gateway_EUI\",\"status\":\"Logs_have_been_sent\"}"

# Subscribe to MQTT topic and process incoming messages
mosquitto_sub -h $BROKER -p $PORT -t $SUB_TOPIC --cafile $CAFILE | while read -r line; do
    # Check if the line contains an action
    if echo "$line" | grep -q '"action":'; then
        # Extract the action value
        action_start=$(echo "$line" | awk -F'"action":"' '{print $2}' | awk -F'"' '{print $1}')
        
        # Process the action
        case "$action_start" in
            "auto_update")
                rm /tmp/.first_boot_updated
				/usr/lib/armbian/armbian-apt-updates 
                mosquitto_pub -h $BROKER -p $PORT -t $PUB_TOPIC --cafile $CAFILE -m "$ack_data"
                ;;
            "package_info")
			
				dpkg -l | grep dragino > /tmp/aptinstalled.txt &
				searchpid=$!
				wait $searchpid
				
                dragino_httpd=$(cat /tmp/aptinstalled.txt | grep -e 'dragino-httpd' | awk '{print $3}')
                dragino_ui=$(cat /tmp/aptinstalled.txt | grep -e 'dragino-ui' | awk '{print $3}')
                draginofwd=$(cat /tmp/aptinstalled.txt | grep -e 'draginofwd' | awk '{print $3}')
                draginoups=$(cat /tmp/aptinstalled.txt | grep -e 'draginoups' | awk '{print $3}')
				dragino_fallback=$(cat /tmp/aptinstalled.txt | grep -e 'dragino-fallback' | awk '{print $3}')
				armbian_bsp_cli_draginohp0z=$(cat /tmp/aptinstalled.txt | grep -e 'armbian-bsp-cli-draginohp0z' | awk '{print $3}')
				linux_image_current_draginohp0z=$(cat /tmp/aptinstalled.txt | grep -e 'linux-image-current-draginohp0z' | awk '{print $3}')

                upload_data="{\"Owner\":\"$Owner\",\"Hostname\":\"$HOSTNAME\",\"Gateway_EUI\":\"$Gateway_EUI\",\"dragino_httpd\":\"$dragino_httpd\",\"dragino_ui\":\"$                dragino_ui\",\"draginofwd\":\"$draginofwd\",\"draginoups\":\"$draginoups\",\"dragino_fallback\":\"$dragino_fallback\",\"armbian_bsp_cli_draginohp0z\":\"$armbian_bsp_cli_draginohp0z\",\"linux_image_current_draginohp0z\":\"$linux_image_current_draginohp0z\"}"
                mosquitto_pub -h $BROKER -p $PORT -t $PUB_TOPIC --cafile $CAFILE -m "$upload_data"
                /usr/local/dragino/monitor/status_publish
                ;;
            "set_server1_address")
                server_address=$(echo "$line" | awk -F'"server_address":"' '{print $2}' | awk -F'"' '{print $1}')

                if [[ -n "$server_address" ]]; then
                    echo "Setting server address to $server_address"
                    uci set gateway.server1.provider='custom'
                    uci set gateway.server1.server_address="$server_address"
                    uci commit gateway
					/usr/local/dragino/reload_iot_server.sh
					sleep 2
					
                    /usr/local/dragino/lora_gw start
                    sleep 2
                    mosquitto_pub -h $BROKER -p $PORT -t $PUB_TOPIC --cafile $CAFILE -m "$ack_data"
                else
                    echo "Invalid server address: $server_address"
                fi
                ;;
            "reboot")
                mosquitto_pub -h $BROKER -p $PORT -t $PUB_TOPIC --cafile $CAFILE -m "$ack_data"
                reboot
                ;;
            "get_latest_log_file")
                echo "get_latest_log_file"
                mosquitto_pub -h $BROKER -p $PORT -t $PUB_TOPIC --cafile $CAFILE -m "$ack_logging"
                touch /tmp/logging.flag

                # Determine server type and collect logs
                if [[ "$server_type" == "station" ]]; then
                    killall tail
                    cat /var/log/station.log >> /tmp/logfile.log
                    tail -f /var/log/station.log >> /tmp/logfile.log &
                else
                    killall logread
                    echo "DMESG:" > /tmp/logfile.log
                    dmesg >> /tmp/logfile.log
                    echo "LOGREAD:" >> /tmp/logfile.log
                    journalctl -u draginofwd  >> /tmp/logfile.log
                    #echo "LOGREAD -f:" >> /tmp/logfile.log
                    #/usr/bin/save_log.sh &
                fi

                #sleep 300
                rm /tmp/logging.flag
                killall logread

                # Upload the log file
                curl -u "$MAC:dragino" -X PUT --upload-file /tmp/logfile.log "https://lns1.thingseye.io/upload/$MAC/logfile.log"
                mosquitto_pub -h $BROKER -p $PORT -t $PUB_TOPIC --cafile $CAFILE -m "$ack_log"
                ;;
            *)
                echo "Unknown action: $action_start"
                ;;
        esac
    fi
done