#!/bin/bash
#
# ESPurna Deploy Script
#
# Copyright (C) 2016 by Xose PĂ©rez <xose dot perez at gmail dot com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

MQTT_HOST=192.168.1.10

function help() {
    echo "Syntax: $0 <device> <target>"
    devices
}

function devices() {
    echo "Defined devices:"
    cat platformio.ini | grep 'device]' | sed 's/\[env:/  - /g' | sed 's/\-device]//g'
}

function valid_ip() {
    local stat=0
    rx='([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])'
    if [[ $ip =~ ^$rx\.$rx\.$rx\.$rx$ ]]; then
        stat=1
    fi
    return $stat
}

# Check arguments
if [ "$#" -ne 2 ]; then
    help
    exit 1
fi
device=$1-device
target=$2

# Get IP
topic=`cat platformio.ini | grep $device -A 2 | grep "topic" | cut -d' ' -f3`
if [ "$topic" == "" ]; then
    echo "Unknown device $device or topic not defined"
    devices
    exit 2
fi

ip=`mosquitto_sub -t $topic -h $MQTT_HOST -N -C 1`
if valid_ip $ip; then
    echo "Could not get a valid IP from MQTT broker"
    exit 3
fi

platformio run -vv -e $device --target $target --upload-port $ip