#!/bin/bash

source functions.sh
source configs.sh

# Pinout for base hat
POWER_OFF=26
W_DISABLE=19

# Control pins
gpio -g mode $POWER_OFF out	#HAT_POWER_OFF
gpio -g mode $W_DISABLE out	#W_DISABLE

gpio -g write $POWER_OFF 0
gpio -g write $W_DISABLE 0


if check_network -eq 0; then 
    debug "PPP chatscript is starting...";
    sudo pon;

    # check default interface
	route | grep ppp | grep default > /dev/null
	PPP_IS_DEFAULT=$?
	if [[ $PPP_IS_DEFAULT -ne 0 ]]; then sudo route add default ppp0; debug "ppp0 is added as default interface manually."; fi
else 
    debug "Network registration is failed!";
fi 

while true; do
    # Checking cellular internet connection
    ping -q -c 1 -s 0 -w $PING_TIMEOUT -I ppp0 8.8.8.8 > /dev/null 2>&1
    PINGG=$?

    if [[ $PINGG -eq 0 ]]; then
        printf "."
    else
        printf "/"
        sleep $DOUBLE_CHECK_WAIT
	    # Checking cellular internet connection
        ping -q -c 1 -s 0 -w $PING_TIMEOUT -I ppp0 8.8.8.8 > /dev/null 2>&1
        PINGG=$?

        if [[ $PINGG -eq 0 ]]; then
            printf "+"
        else
	        debug "Connection is down, reconnecting..."
            if check_network -eq 0; then sleep 0.1; else debug "Network registration is failed!"; fi
	        sudo pon

            # check default interface
            route | grep ppp | grep default > /dev/null
            PPP_IS_DEFAULT=$?
            if [[ $PPP_IS_DEFAULT -ne 0 ]]; then sudo route add default ppp0; debug "ppp0 is added as default interface manually."; fi
	    fi
    fi
	sleep $INTERVAL
done
