#!/bin/bash
# Usage
#	push_device_info_to_server <server> <mac>
#

config_dir=/etc/nyquist
temp_path="/run"
envfile="/run/appliance-env"
server_address=$1
server_path="new"
filename=$2.new
device_ip=(`ip addr show primary | sed -n -e '/127\.0\.0\.1/d;s/\s*inet\s\+\(\([[:digit:]]\+\.\)\+[[:digit:]]\+\).*/\1/p'`)
device_mac=$2

[ -f ${envfile} ] && . ${envfile}

[ -f ${config_dir}/device_type ] && . ${config_dir}/device_type
: ${device_id:=10}

WBCDETECTED=0

if [ -e ${config_dir}/wbcdetected ]; then
    WBCDETECTED=1
fi

if [ ${APPLIANCE_PART:-$device_id} == "nq-s810v3" ] || [ ${APPLIANCE_PART:-$device_id} == "nq-s810v2" ]; then
        #echo "This is a Gen 3 VoIP"
        # TODO: Get CAN Display status, if display is connected, send different appliance part ID
        if [ $WBCDETECTED == 1 ]; then
                #echo "This is a WBC"
                echo -e "MAC=${device_mac}\nIP=${device_ip[0]:-0.0.0.0}\nID=nq-wbc\nSNO=${APPLIANCE_SERIAL}" > ${temp_path}/${filename}
        else
                #echo "Normal appliance part reporting"
                echo -e "MAC=${device_mac}\nIP=${device_ip[0]:-0.0.0.0}\nID=${APPLIANCE_PART:-$device_id}\nSNO=${APPLIANCE_SERIAL}" > ${temp_path}/${filename}
        fi

else
        #echo "Normal appliance part reporting"
        echo -e "MAC=${device_mac}\nIP=${device_ip[0]:-0.0.0.0}\nID=${APPLIANCE_PART:-$device_id}\nSNO=${APPLIANCE_SERIAL}" > ${temp_path}/${filename}
fi


# Create info file
read results < <(tftp <<< "put ${temp_path}/${filename} ${server_address}:${server_path}/${filename}")
rc=$?

unlink ${temp_path}/${filename}

if [ "${results/*Sent*/sent}" = "sent" ]; then
	exit 0
elif [ $rc -ne 0 ]; then
	exit 2
fi

exit 1
