#!/bin/sh
#
# b6m-spread
#
# Copyright (C) 2011-2013 Simó Albert i Beltran
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# wget command
WGET="wget -O - -q -t 2 -T 5"

if wget --help 2>&1 | head -1 | grep -q "^BusyBox "
then
	WGET=":"
fi

# bmx6 run dir
BMX6_RUN_DIR="/var/run/bmx6"
BMX6_SEND_SMS_DIR="$BMX6_RUN_DIR/sms/sendSms"
BMX6_JSON_DIR="$BMX6_RUN_DIR/json"

BMX6_SEND_SMS_MAX_LENGTH="240"

# Program name.
PROG_NAME="$(basename $0)"

# Data directory
DATA_DIR="/tmp/$PROG_NAME"

# Hysteresis for link quality level.
LINK_HYSTERESIS=5

# Maximum concurrent processes to send data.
MAX_CONCURRENT_SEND_DATA=5

# Debug messages.
DEBUG=${DEBUG:-false}

##
# Translate a value from one range to other range
#	value to translate $1
#	input range ($2, $3)
#	output range ($4, $5)
#
translateRange()
{
	echo $@ | awk '
{
	if ($1 <= $2)
	{
		print $4;
	}
	else if ($1 >= $3)
	{
		print $5;
	}
	else
	{
		print ( $1 * ( $5 - $4 ) + $3 * $4 - $2 * $5 ) / ( $3 - $2 );
	}
}'
}

log()
{
	if $DEBUG
	then
		logger -t $PROG_NAME "$@"
	fi
}

getGeoposition()
{
	local mode="$(uci -q get b6m-spread.geoposition.mode)"
	local latitude="$(uci -q get b6m-spread.geoposition.latitude)"
	local longitude="$(uci -q get b6m-spread.geoposition.longitude)"

	if [ -z "$latitude" ] || [ -z "$longitude" ] || [ "$mode" == "swia" ] && [ "$mode" != "dyntest" ] && [ "$mode" != "mac" ]
	then
		swia_json="$(swia)"
		latitude="$(echo "$swia_json" | sed -n -e 's/{"location":{"latitude":\(.*\),"longitude":.*,"accuracy":.*},"access_token":".*"}/\1/gp')"
		longitude="$(echo "$swia_json" | sed -n -e 's/{"location":{"latitude":.*,"longitude":\(.*\),"accuracy":.*},"access_token":".*"}/\1/gp')"
		if [ -n "$latitude" ] && [ -n "$longitude" ]
		then
			swia_latitude="$latitude"
			swia_longitude="$longitude"
		else
			latitude="$swia_latitude"
			longitude="$swia_longitude"
		fi
	fi

	# Get default minium and maxium latitude and longitude.
	if [ "$mode" == "dyntest" ] || [ "$mode" == "mac" ] || [ -z "$latitude" ] || [ -z "$longitude" ]
	then
		local latitudeMin="$(uci -q get b6m-spread.geolocationDefault.latitudeMin)"
		[ -z "$latitudeMin" ] && latitudeMin="-0.01"

		local latitudeMax="$(uci -q get b6m-spread.geolocationDefault.latitudeMax)"
		[ -z "$latitudeMax" ] && latitudeMax="0.01"

		local longitudeMin="$(uci -q get b6m-spread.geolocationDefault.longfitudeMin)"
		[ -z "$longitudeMin" ] && longitudeMin="-0.01"

		local longitudeMax="$(uci -q get b6m-spread.geolocationDefault.longitudeMax)"
		[ -z "$longitudeMax" ] && longitudeMax="0.01"
	fi

	# Create an position using the MAC address.
	if [ "$mode" == "mac" ] || [ -z "$latitude" ] || [ -z "$longitude" ]
	then
		if [ -z "$mac_latitude" ] || [ -z "$mac_longitude" ]
		then
			local mac="$(ip link show | grep -m 1 "link/ether" | awk '{print $2}')"

			mac_latitude="$(echo $mac | md5sum | sed -e "s/[a-z]//g" -e "s/^\(..\)\(.*\)$/\1/g")"
			[ -z "$mac_latitude" ] && mac_latitude="0"
			mac_latitude="$(translateRange $mac_latitude 0 99 $latitudeMin $latitudeMax)"

			mac_longitude="$(echo $mac | md5sum | md5sum | sed -e "s/[a-z]//g" -e "s/^\(..\)\(.*\)$/\1/g")"
			[ -z "$mac_longitude" ] && mac_longitude="0"
			mac_longitude="$(translateRange $mac_longitude 0 99 $longitudeMin $longitudeMax)"
		fi
		latitude="$mac_latitude"
		longitude="$mac_longitude"
	fi

	if [ "$mode" == "dyntest" ]
	then
		# Set dynamic random latitude and longitude
		latitude="$(dd if=/dev/urandom count=1 2> /dev/null | md5sum | sed -e "s/[a-z]//g" -e "s/^\(..\)\(.*\)$/\1/g")"
		[ -z "$latitude" ] && latitude="0"
		latitude="$(translateRange $latitude 0 99 $latitudeMin $latitudeMax)"

		longitude="$(dd if=/dev/urandom count=1 2> /dev/null | md5sum | sed -e "s/[a-z]//g" -e "s/^\(..\)\(.*\)$/\1/g")"
		[ -z "$longitude" ] && longitude="0"
		longitude="$(translateRange $longitude 0 99 $longitudeMin $longitudeMax)"
	fi

	output="{ \"b6mGeoposition\" : { \"longitude\" : \"$longitude\", \"latitude\" : \"$latitude\", \"mode\": \"$mode\" } }"
}

makeLinksHistory()
{
	# input
	# quality globalId viaDev

	# output
	# qualityLevel count globalId viaDev

	local oldLinksHistory="$linksHistory"
	linksHistory=""

	while [ -n "$linksRaw" ]
	do
		link="$(echo "$linksRaw" | head -1)"
		linksRaw="$(echo "$linksRaw" | sed -e 1d)"
		local newQuality="${link%% *}"
		local newLink="${link#* }"
		local oldQualityLevel="$(echo "$oldLinksHistory" | awk '/'"$newLink"'$/{print $1}')"
		
		if [ "$newQuality" -gt 90 ]
		then
			newQualityLevel=3
		
		elif [ "$newQuality" -gt 50 ]
		then
			newQualityLevel=2
		else
			newQualityLevel=1
		fi
		oldQualityLevel=${oldQualityLevel:-$newQualityLevel}
		
		local oldCount="$(echo "$oldLinksHistory" | awk '/'"$newLink"'$/{print $2}')"
		oldCount=${oldCount:-0}
		
		newCount=$(($newQualityLevel - $oldQualityLevel))
		if [ $newCount != 0 ]
		then
			newCount=$(($oldCount + $newCount))
			if [ $newCount -lt -$LINK_HYSTERESIS -a $oldQualityLevel -gt 1 ]
			then
				newQualityLevel=$(($oldQualityLevel - 1))
				newCount=0
			elif [ $newCount -gt $LINK_HYSTERESIS -a $oldQualityLevel -lt 3 ]
			then
				newQualityLevel=$(($oldQualityLevel + 1))
				newCount=0
			else
				newQualityLevel=$oldQualityLevel
			fi
		fi
		
		if [ -n "$linksHistory" ]
		then
			linksHistory="$linksHistory
"
		fi
		
		linksHistory="$linksHistory$newQualityLevel $newCount $newLink"

	done
}

makeLinksJSON()
{
	# input
	# qualityLeval count globalId viaDev

	output=""
	
	local links="$linksHistory"
	while [ -n "$links" ]
	do
		link="$(echo "$links" | head -1)"
		links="$(echo "$links" | sed -e "1d")"
		if [ -n "$output" ]
		then
			output="$output, "
		fi

		local quality="${link%% *}"
		if [ "$quality" = 3 ]
		then
			quality=good
			
		elif [ "$quality" = 2 ]
		then
			quality=normal
		else
			quality=bad
		fi
		local count="${link#* }"
		count="${count%% *}"
		
		output="$output { ${link#* * } \"quality\": \"$quality\" }"
				
	done

	output="{ \"b6mLinks\" : [ $output ] }"
}

getLinksCommand()
{
	#TODO sort by quality
	output=""
	bmx6 -c --links | grep -v " ERROR " | sed -e "1,2d" | while read link
	do
		globalId="$(echo $link | awk '{print $1}')"
		viaDev="$(echo $link | awk '{print $3}')"
		rate="$(echo $link | awk '{printf "%d",($4+$5)/2}')"
		if [ "$rate" -gt "80" ]
		then
			quality="good"
		else
			if [ "$rate" -gt "20" ]
			then
				quality="normal"
			else
				# if [ "$rate" -lt "20" ]
				quality="bad"
			fi
		fi
		[ -n "$output" ] && output="$output, "
		output="$output { \"globalId\": \"$globalId\", \"viaDev\": \"$viaDev\", \"quality\": \"$quality\" }"
	done
	output="{ \"b6mLinks\" : [ $output ] }"

}

getLinksJSON()
{
	# linksRaw
	# quality globalId viaDev

	linksRaw="$(cat "$BMX6_JSON_DIR/links" | awk -v RS='}' '
{
	globalId="";
	viaDev="";
	rxRate="";
	txRate="";
};
match($0,/"?globalId"?: ?"?[^",]*"?,?/){globalId=substr($0,RSTART,RLENGTH)};
match($0,/"?viaDev"?: ?"?[^",]*"?,?/){viaDev=substr($0,RSTART,RLENGTH)};
match($0,/"?"?rxRate"?: ?"?[^",]*"?,?/){rxRate=substr($0,RSTART,RLENGTH)};
match(rxRate,/: .*/){rxRate=substr(rxRate,RSTART+2,RLENGTH-3)};
match($0,/"?"?txRate"?: ?"?[^",]*"?,?/){txRate=substr($0,RSTART,RLENGTH)};
match(txRate,/: .*/){txRate=substr(txRate,RSTART+2,RLENGTH-3)};
{
	if(globalId)
	{
		print ( rxRate < txRate ? rxRate : txRate ) " " globalId " " viaDev;
	}
};
' | sort -rn)"

	makeLinksHistory
	makeLinksJSON

}

getLinks()
{
	if [ -s "$BMX6_JSON_DIR/links" ]
	then
		getLinksJSON
	else
		getLinksCommand
	fi
}

max_concurrent_processes_reached()
{
	local jobs="$(jobs)"
	local num_jobs="$(echo "$jobs" | grep -v "^\[[0-9]\+\][-+ ]  \(Done\(([0-9]\+)\)\?\|Terminated\)\b" | wc -l)"
	if [ "$num_jobs" -ge "$MAX_CONCURRENT_SEND_DATA" ]
	then
		return 0
	else
		return 1
	fi
}

wait_max_concurrent_processes()
{
	while max_concurrent_processes_reached
	do
		log "maximum concurrent processes to send data reached."
		sleep 1
	done
}

methodHttp()
{
	dataType="$(echo "$*" | sed -n -e 's/^{ \?"\?\([^" :]\+\)"\? \?:.*$/\1/gp')"
	[ -z "$globalId" -o -z "$dataType" ] && return 1
	mkdir -p $DATA_DIR/$globalId \
	&& echo "$*" > $DATA_DIR/$globalId/$dataType \
	&& log "saved local data to $DATA_DIR/$globalId/$dataType"

	jobs -p | xargs -r kill

	for originator in $(ls $BMX6_RUN_DIR/json/originators)
	do
		if [ "$originator" != "$globalId" ]
		then
			wait_max_concurrent_processes

			primaryIp="$(cat $BMX6_RUN_DIR/json/originators/$originator | sed -n -e 's/{ "globalId": "'$originator'", .*"primaryIp": "\([^"]*\)".* }/\1/gp')"
			$WGET --post-data="action=set&data_type=$dataType&global_id=$globalId&data=$*" http://[$primaryIp]/cgi-bin/$PROG_NAME-http \
			&& log "sent data to $originator $*" &
		fi
	done
	return 0
}

sortLinks()
{
	echo -n "{ \"b6mLinks\" : [ "
	echo -n "$@" \
	| tr -d "\n" \
	| sed -n -e "s/^ *{ *\"\?b6mLinks\"\? *: \[ *\(.*\) *\] *} *$/\1/gp" \
	| sed -e "s/} *,\? */\n/g" \
	| sort \
	| sed -e "s/$/}, /g" \
	| tr -d "\n" \
	| sed -e "s/, $//g"
	echo -n " ] }"
}

truncateLinks()
{
	local linksTruncatedNew="$@"
	while true
	do
		local linksGzipedNew="$(echo "$linksTruncatedNew" | gzip)"
		local linksGzipedNewLength="$(echo "$linksGzipedNew" | wc -c)"
		log "linksGzipedNewLength $linksGzipedNewLength"
		if [ "$linksGzipedNewLength" -gt "$BMX6_SEND_SMS_MAX_LENGTH" ]
		then
			log "discard the worst link"
			linksTruncatedNew="$(echo "$linksTruncatedNew" | sed -n -e 's/^\({ *"\?b6mLinks"\? *: *\[\? *{.*}\)\(,\? *{[^}]*}\)\( *\]\? *}\)$/\1\3/gp')"
		else
			break
		fi
	done
	echo "$linksTruncatedNew"
}

method="$(uci -q get $PROG_NAME.general.method)"
if [ -z "$method" ] || [ "$method" = "sms" ]
then
	while ! bmx6 -c --syncSms b6mGeoposition --syncSms b6mLinks.gz
	do
		sleep 5
	done
fi

while true
do
	if [ "$method" = "http" ]
	then
		globalIdNew="$(cat $BMX6_RUN_DIR/json/status | sed -n -e 's/{ "status": { .*"globalId": "\([^"]*\)".* } }/\1/gp')"
		if [ "$globalId" != "$globalIdNew" ]
		then
			log "new globalId"
			geoposition=""
			links=""
			globalId="$globalIdNew"
		fi
	fi
	
	getGeoposition
	geopositionNew="$output"
	if [ "$geoposition" != "$geopositionNew" ]
	then
		log "new geolocation: $geopositionNew"
		if [ "$method" = "http" ]
		then
			methodHttp "$geopositionNew"
		else
			#if [ "$method" = "sms" ]
			echo "$geopositionNew" > "$BMX6_SEND_SMS_DIR/b6mGeoposition" \
			&& log "sms file writed $BMX6_SEND_SMS_DIR/b6mGeoposition"
		fi \
		&& geoposition="$geopositionNew"
	fi

	getLinks
	linksNew="$output"
	if [ "$links" != "$linksNew" ]
	then
		log "new links"
		if [ "$method" = "http" ]
		then
			linksSortedNew="$(sortLinks "$linksNew")"
			if [ "$linksSorted" != "$linksSortedNew" ]
			then
				methodHttp "$linksNew"
				linksSorted="$linksSortedNew"
			fi
		else
			#if [ "$method" = "sms" ]
			linksTruncatedNew="$(truncateLinks "$linksNew")"
			linksTruncatedNew="$(sortLinks "$linksTruncatedNew")"
			if [ "$linksTruncated" != "$linksTruncatedNew" ]
			then
				echo "$linksTruncatedNew" | gzip > "$BMX6_SEND_SMS_DIR/b6mLinks.gz" \
				&& linksTruncated="$linksTrunkatedNew" \
				&& log "sms file writed $BMX6_SEND_SMS_DIR/b6mLinks.gz"
			fi
		fi \
		&& links="$linksNew"
	fi

	interval="$(uci -q get b6m-spread.general.interval)"
	[ -z "$interval" ] && interval="2"
	sleep $interval
done
