#!/bin/bash

# -- check if boxnet is running
RES1=`pgrep boxnet | wc -l`
RES2=`pgrep wipelte | wc -l`
RES=$(($RES1+$RES2))
BR=0
while [[ $RES -ne 0 ]] && [[ ${1} != "stop" ]]; do
	BR=1
	RES1=`pgrep boxnet | wc -l`
	RES2=`pgrep wipelte | wc -l`
	RES=$(($RES1+$RES2))
	sleep 1
done
if [[ $BR -eq 1 ]]; then
	sleep 5
fi

# -------------------------------------------------------------------
# -- Globals
# -------------------------------------------------------------------

MYPID=$$
BASENAME=${0##*/}
PREFIX="${BASENAME} [${MYPID}]"
DEV="/dev/ttyACM0"
IFNAME="ppp5"
BAUD=19200

RUNDIR="/var/phion/run/boxnet/UMTS"
[ ! -d ${RUNDIR} ] && mkdir -p ${RUNDIR}

RAMDIR="/dev/shm/boxnet/3G"
[ ! -d ${RAMDIR} ] && mkdir -p ${RAMDIR}

STATEFILE="lte.state"
TERMINATE=0
RECONNECT=0
ERRORS=0
PINGIP=(`/epb/ltectrl -p | grep "IP:" | cut -d ":" -f 2 | tr " " "\n"`)
LTECTRLLOCKFILE="/tmp/lte.lock"
LTECTRL="/epb/ltectrl"
PINFILE="/tmp/ltepin.txt"
PINLOCKFILE="/tmp/ltepin.lock"

ETIMEOUT=110
EIFMISS=220
EIPMISS=230

/etc/phion/bin/boxconf_rollout.net1 /opt/phion/config/active/boxnet.conf /tmp/boxnetoldconfig
source /tmp/boxnetoldconfig
DFLTRT=${box_umts_DFLTRT_1:-y}
M40MONDIS=${box_umts_M40MON_1:-0}
rm -f /tmp/boxnetoldconfig &> /dev/null

DEBUG=0
if [[ $DEBUG -eq 1 ]]; then
	LTECTRL="/epb/ltectrl -v"
fi

################################
# FIRST: set some Variables

if [ -f /etc/phion/phion.sh ]; then
	source /etc/phion/phion.sh
fi

if [ -f /etc/phion/options ]; then
	source /etc/phion/options
fi

PMODPATH="/opt/phion/modules/box/boxnet"
[ -f ${PMODPATH}/moddefs.conf ] && source ${PMODPATH}/moddefs.conf
	MYLOGFLE="box_Network_umts"

# -------------------------------------------------------------------
# Logging
# -------------------------------------------------------------------
if [ -f /etc/phion/functions ]; then
	source /etc/phion/functions
	logerror="LogError $MYLOGFLE"
else
	logerror="echo"
fi

function logmsg
{
	if [[ ${1} == "Debug" ]] && [[ $DEBUG -ne 1 ]]; then
		return
	fi

	$logerror ${1} ${2}
	if [[ $DEBUG -eq 1 ]]; then
		DATE=`date +'%Y %m %d %H:%M:%S'`
		echo "${DATE} ${1} - ${2}"
	fi
}

# -------------------------------------------------------------------
# signal handler
# -------------------------------------------------------------------
function fEXIT
{
	${LTECTRL} -d
	logmsg "Info" "${PREFIX}: openlte stopped"
	exit 0
}

function fTERM
{
	logmsg "Debug" "${PREFIX}: I will terminate"
	TERMINATE=1
}

function fCHANGE
{
	logmsg "Debug" "${PREFIX}: I got a notification"
	LOOPCOUNTER=60
	kill -TERM $(ps -C ltectrl -o pid=)
}

# -------------------------------------------------------------------
# check routes
# -------------------------------------------------------------------
function checkRoutes
{
	logmsg "Debug" "${PREFIX}: check routes"

	# -- route in table main
	ip r | grep ${IFNAME} &> /dev/null
	RMAIN=$?
	if [[ $RMAIN -ne 0 ]]; then
		logmsg "Error" "${PREFIX}: route in table \"main\" not found"
	fi

	# -- route in table default
	if [[ ${DFLTRT} == "y" ]]; then
		ip r show table default | grep ${IFNAME} &> /dev/null
		RDFLT=$?
		if [[ $RDFLT -ne 0 ]]; then
			logmsg "Error" "${PREFIX}: route in table \"default\" not found"
		fi
	fi

	if [[ $RMAIN -ne 0 ]] || [[ $RDFLT -ne 0 ]]; then
		${LTECTRL} -i
	fi
}

# -------------------------------------------------------------------
# check connection
# -------------------------------------------------------------------
function checkConnect
{
	logmsg "Debug" "${PREFIX}: check connection"

	# -- exists ppp5???
	ifconfig ${IFNAME} &> /dev/null
	if [[ $? -ne 0 ]]; then
		logmsg "Error" "${PREFIX}: interface ${IFNAME} not found"
		ERRORS=$(($ERRORS+1))
		return $EIFMISS
	fi

	# -- has ppp5 an IP???
	RES=`ifconfig ${IFNAME} 2> /dev/null | grep "inet" | sed -e 's/^[[:space:]]*//' | cut -d' ' -f2`
	if [[ -z "${RES}" ]]; then
		logmsg "Error" "${PREFIX}: no IP found"
		ERRORS=$(($ERRORS+1))
		return $EIPMISS
	fi

	# -- check ping address list
	logmsg "Debug" "${PREFIX}: Num ping addresses: ${#PINGIP[*]}"
	if [[ ${#PINGIP[*]} -lt 1 ]]; then
		PINGIP=(`/epb/ltectrl -p | grep "IP:" | cut -d ":" -f 2 | tr " " "\n"`)
	fi

	# -- testing connection with ping
	RES=0
	for ((i=0; i<${#PINGIP[*]}; i++)); do
		logmsg "Debug" "${PREFIX}: sending ping to ${PINGIP[$i]}"

		RES=`ping ${PINGIP[$i]} -I ${IFNAME} -c 5 -w 5 -W 1 -q | grep received | cut -d',' -f 2 | cut -d' ' -f 2`
		logmsg "Debug" "${PREFIX}: Ping result: ${RES}"
		if [[ $RES -le 0 ]]; then
			logmsg "Error" "${PREFIX}: cannot reach ${PINGIP[$i]}"
		else
			break
		fi
	done

	RET=0
	if [[ $RES -le 0 ]]; then
		TOERRORS=$(($TOERRORS+1))
		ERRORS=$(($ERRORS+1))
		RET=$ETIMEOUT
	else
		ERRORS=0
		TOERRORS=0
	fi

	checkRoutes

	echo $ERRORS

	logmsg "Debug" "${PREFIX}: checkConn - Err: $ERRORS, Ret: $RET"
	return $RET
}

# -------------------------------------------------------------------
# check time of lockfile
# -------------------------------------------------------------------
function checklock
{
	logmsg "Debug" "${PREFIX}: check lock"

	if [[ ! -f ${LTECTRLLOCKFILE} ]]; then
		return 0
	fi

	MODTIME=`date -r ${LTECTRLLOCKFILE} "+%s"`
	TIME=`date "+%s"`

	logmsg "Debug" "${PREFIX}: MODTIME:${MODTIME}# TIME:${TIME}#"
	if ! [[ ${MODTIME} =~ ^[0-9]+$ ]]; then
		logmsg "Warning" "${PREFIX}: cannot read modification time of the ltectrl lock file"
		return 0
	fi

	TIMEDIFF=$(($TIME-$MODTIME))

	# if older than 5min
	if [[ $TIMEDIFF -ge 300 ]]; then
		logmsg "Warning" "${PREFIX}: found old lock file"
		RES=`pgrep ltectrl | wc -l`
		if [[ $RES -gt 1 ]]; then
			logmsg "Info" "${PREFIX}: kill left ltectrl processes"
			kill -9 $(ps -C ltectrl -o pid=)  &> /dev/null &
			sleep 2
			RES=`pgrep serialCommunicator | wc -l`
			if [[ $RES -gt 1 ]]; then
				logmsg "Info" "${PREFIX}: kill left serialCommunicator processes"
				kill -9 $(ps -C serialCommunicator -o pid=)  &> /dev/null &
				sleep 2
			fi
			checkComm
			if [[ $? -ne 0 ]]; then
				logmsg "Error" "${PREFIX}: communication problems with /dev/ttyACM0"
				resetmodem
			fi
		fi

		logmsg "Warning" "${PREFIX}: deleting old lock file"
		rm -f /tmp/lte.lock &> /dev/null

		return 1
	fi

	return 0
}

# -------------------------------------------------------------------
# check communicatio to modem
# -------------------------------------------------------------------
function checkComm
{
	logmsg "Debug" "${PREFIX}: check communication to modem"

	if [[ -f ${LTECTRLLOCKFILE} ]] || [[ ${M40MONDIS} -eq 1 ]]; then
		if [[ ${M40MONDIS} -eq 1 ]]; then
			logmsg "Debug" "${PREFIX}: Monitoring of the communication between box and modem is disabled"
		fi
		return 0
	fi

	/epb/serialCommunicator -d /dev/ttyACM0 -t 2 -c ATZ
	if [[ $? -eq $ETIMEOUT ]]; then
		logmsg "Error" "${PREFIX}: communication problems with /dev/ttyACM0"
		return 1
	fi

	return 0
}

# -------------------------------------------------------------------
# reset modem
# -------------------------------------------------------------------
function resetmodem
{
	logmsg "Info" "${PREFIX}: start reseting the modem"

	[ -f ${RUNDIR}/${STATEFILE} ] && {
		read STATE < ${RUNDIR}/${STATEFILE}
	}

	echo "disconnect" > ${RUNDIR}/${STATEFILE}

	sleep 5

	RES=`pgrep ltectrl | wc -l`
	if [[ $RES -gt 1 ]]; then
		logmsg "Info" "${PREFIX}: kill left ltectrl processes"
		kill -9 $(ps -C ltectrl -o pid=)  &> /dev/null &
		sleep 2
	fi

	rm -f /tmp/lte.lock &> /dev/null

	${LTECTRL} -r

	sleep 2

	logmsg "Info" "${PREFIX}: restore old modem state"
	echo "${STATE}" > ${RUNDIR}/${STATEFILE}

	return 0
}

# -------------------------------------------------------------------
# main
# -------------------------------------------------------------------
# -------------------------
# -- control mode
# -------------------------
if [[ -n "${1}" ]] && [[ "${1}" != "&" ]]; then
	case ${1} in
		start) echo "on" > ${RUNDIR}/${STATEFILE};;
		stop) echo "off" > ${RUNDIR}/${STATEFILE};;
		reconnect) echo "reconnect" > ${RUNDIR}/${STATEFILE};;
		disconnect) echo "disconnect" > ${RUNDIR}/${STATEFILE};;
		reset) resetmodem;;
		help)
			echo "usage: ${BASENAME} <option>"
			echo "options:"
			echo "   start = start openlte as daemon"
			echo "   stop = stop openlte daemon"
			echo "   reconnect = reconnect the modem to network"
			echo "   disconnect = disconnect the modem from network"
			exit 0
			;;
	esac

	[ -f ${RUNDIR}/openlte.pid ] && {
		read PID < ${RUNDIR}/openlte.pid
	}
	RES=`pgrep openlte | grep "${PID}" | wc -l`
	if [[ ${1} != "stop" ]] && [[ -z "${PID}" || $RES == 0 ]]; then
		rm -f ${RUNDIR}/openlte.pid &> /dev/null

		/epb/openlte &
	else
		kill -ABRT ${PID}
	fi

	exit 0
fi

# -------------------------
# -- check running daemon
# -------------------------
[ -f ${RUNDIR}/openlte.pid ] && {
	read PID < ${RUNDIR}/openlte.pid
}
RES=`pgrep openlte | grep "${PID}" | wc -l`
if [[ $RES -eq 1 ]]; then
	logmsg "Warning" "${PREFIX}: an other openlte process is running"
	exit 0
fi

trap fEXIT EXIT
trap fTERM TERM INT KILL
trap fCHANGE HUP ABRT

echo "${MYPID}" > ${RUNDIR}/${BASENAME}.pid

[ -f ${RUNDIR}/${STATEFILE} ] && {
	echo "on" > ${RUNDIR}/${STATEFILE}
}

LOOPCOUNTER=60
CONTYPECOUNTER=0
COMMERRORS=0
TOERRORS=0

while [[ $TERMINATE -eq 0 ]]; do
	if [[ $LOOPCOUNTER -ge 60 ]]; then
		CONTYPECOUNTER=$(($CONTYPECOUNTER+1))

		checklock

		[ -f ${RUNDIR}/${STATEFILE} ] && {
			read STATE < ${RUNDIR}/${STATEFILE}
		}

		logmsg "Debug" "${PREFIX}: LTE State: ${STATE}"

		case ${STATE} in
			on)
				if [[ -f ${PINFILE} ]] || [[ -f ${PINLOCKFILE} ]]; then
					LOOPCOUNTER=0
					${LTECTRL} -l &
				elif [[ ! -f ${LTECTRLLOCKFILE} ]]; then
					LOOPCOUNTER=0

					checkComm
					if [[ $? -ne 0 ]]; then
						COMMERRORS=$(($COMMERRORS+1))
						if [[ $COMMERRORS -ge 3 ]]; then
							COMMERRORS=0
							resetmodem
						fi
					else
						COMMERRORS=0
					fi

					checkConnect
					RET=$?
					logmsg "Debug" "${PREFIX}: RET: ${RET}, Err: ${ERRORS}"
					# handle timeouts
					if [[ $RET -eq $ETIMEOUT ]] && [[ $TOERRORS -ge 2 ]]; then
						if [[ $TOERRORS -ge 5 ]]; then
							ERRORS=0
							TOERRORS=0
							${LTECTRL} -r &
						else
							${LTECTRL} -i &
						fi
					# interface ppp5 is missing
					elif [[ $RET -eq $EIFMISS ]]; then
						${LTECTRL} &
					# IP missing, try to get an IP
					elif [[ $RET -eq $EIPMISS ]] && [[ $ERRORS -le 3 ]]; then
						PUKRET=`ltectrl -l`
						if [[ $PUKRET -eq 1 ]]; then
							continue
						fi

						if [[ $ERRORS -lt 2 ]]; then
							${LTECTRL} -i &
						else
							${LTECTRL} &
						fi
					# handle all other errors
					elif [[ $RET -ne 0 ]] && [[ $ERRORS -ge 3 ]]; then
						if [[ $ERRORS -gt 5 ]]; then
							ERRORS=0
							${LTECTRL} -r &
						else
							${LTECTRL} &
						fi
					# every 5 min check connection type and RSSI
					elif [[ $CONTYPECOUNTER -gt 5 ]] && [[ $COMMERRORS -eq 0 ]]; then
						CONTYPECOUNTER=0
						${LTECTRL} -s &
					# no errors
					elif [[ $RET -eq 0 ]]; then
						ERRORS=0
						TOERRORS=0
					fi
				fi
				;;

			off)
				TERMINATE=1
				ERRORS=0
				;;

			reconnect)
				${LTECTRL} -n &
				;;
		
			disconnect)
				${LTECTRL} -d &
				;;
		esac
	fi

	if [[ $ERRORS -gt 1 ]] && [[ $LOOPCOUNTER -eq 0 ]]; then
		LOOPCOUNTER=30
	fi

	sleep 1

	LOOPCOUNTER=$(($LOOPCOUNTER+1))
done

echo "off" > ${RUNDIR}/${STATEFILE}

rm -f ${RUNDIR}/${BASENAME}.pid &> /dev/null

