#!/bin/bash
#
# This script will check for a change in IP address
#
# $@ = One or more IP addresses/DNS names to include in the SSL cert
#
# (C) Copyright 2020-2022, Bogen Communications LLC. All rights reserved.
#

PATH=/bin:/usr/bin:/sbin/:/usr/sbin
BOARD_NAME=$(cat /sys/devices/platform/bone_capemgr/slot-0/board-name)
NYQUIST_DIR=/etc/nyquist
NETWORK_INFO_FILE=$NYQUIST_DIR/network_info
NAMED_PIPE_FILE=/tmp/nyq_mqtt_read
SSL_CERT_LOCK=/tmp/update-ssl-cert.lock
while true; do
    IP_ADDR=$(ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1')

    # Skip this iteration if no IP address is available yet
    if [ -z "$IP_ADDR" ]; then
        sleep 30
        continue
    fi

    if [ ! -f "$NETWORK_INFO_FILE" ]; then
        echo "$IP_ADDR" > $NETWORK_INFO_FILE
        #echo "File not found....writing $IP_ADDR to $NETWORK_INFO_FILE"
        # Use flock to prevent concurrent cert updates; wait for any running instance to finish
        (flock $SSL_CERT_LOCK /usr/local/bin/update-ssl-cert $IP_ADDR) &
        if [ $BOARD_NAME == "NQ-GA10PV" ]; then
            systemctl restart display
        fi
        printf "change_ip\n" >> $NAMED_PIPE_FILE
    else
        #FILE EXISTS, if IP is different then we update and run the ssl certificate update
        OLD_IP_ADDR=$(<$NETWORK_INFO_FILE)
        #echo "Old IP address is $OLD_IP_ADDR from $NETWORK_INFO_FILE"
        if [ "$IP_ADDR" != "$OLD_IP_ADDR" ]; then
            #echo "IP address has changed from $OLD_IP_ADDR to $IP_ADDR"
            echo "$IP_ADDR" > $NETWORK_INFO_FILE
            # Use flock to prevent concurrent cert updates; wait for any running instance to finish
            (flock $SSL_CERT_LOCK /usr/local/bin/update-ssl-cert $IP_ADDR) &
            if [ $BOARD_NAME == "NQ-GA10PV" ]; then
                systemctl restart display
            fi
            printf "change_ip\n" >> $NAMED_PIPE_FILE
        fi
    fi
    sleep 30
done

exit 0
