#!/bin/sh
#
# b6m JSONP interface
#
# Copyright (C) 2011-2012 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/>.
#
# Version 0.3.20120513.0.0

# Set wget command
WGET="wget -O - -q -t 1 -T 30"

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

# Set bmx6 run dir
BMX6_RUN_DIR=/var/run/bmx6

MAX_LENGTH_OUTPUT="40950"

DATA_DIR="/tmp/b6m-spread"

timeout()
{
	timeout=$1
	shift

	echo "
		timeout_pid=\$\$

		{
			$@
			kill \$timeout_pid 2> /dev/null
		}&
		child_pid=\$!

		sleep $timeout
		echo TIMEOUT 1>&2
		kill \$child_pid 2> /dev/null
		sleep 1
		kill -9 \$child_pid 2> /dev/null
	" | sh
}

b6m_spread_http_json()
{
	logger -t $(basename $0) "http requested $1 $2"

	if [ ! -s "$DATA_DIR/$1/$2" -a "$1" != "$globalId" ]
	then
		local primaryIp="$(cat $BMX6_RUN_DIR/json/originators/$1 | sed -n -e 's/{ "globalId": "'$1'", .*"primaryIp": "\([^"]*\)".* }/\1/gp')"
		if [ -z "$primaryIp" ]
		then
			logger -t $(basename $0) "no primaryIp for $1"
		else
			local url="http://[$primaryIp]/cgi-bin/b6m-spread-http?action=get&global_id=$1&data_type=$2"
			logger -t $(basename $0) "data from $url"
			mkdir -p $DATA_DIR/$1 \
			&& $WGET "$url" > $DATA_DIR/$1/$2 &
		fi
	fi
	if [ -s "$DATA_DIR/$1/$2" ]
	then
		cat $DATA_DIR/$1/$2 \
		&& logger -t $(basename $0) "data from $DATA_DIR/$1/$2"
	else
		logger -t $(basename $0) "no data for $1 $2"
	fi
}

bmx6_json()
{
	logger -t $(basename $0) "requested $id $1"

	if [ -s $BMX6_RUN_DIR/json/$1 ]
	then
		if [ -d $BMX6_RUN_DIR/json/$1 ]
		then
			if [ -s $BMX6_RUN_DIR/json/$1/$id ]
			then
				output="$(cat $BMX6_RUN_DIR/json/$1/$id)"
			else
				output=""
				for item in $BMX6_RUN_DIR/json/$1/*
				do
					[ -n "$output" ] && output="$output, "
					output="$output $(cat $item)"
				done
			fi
		else
			if [ -s $BMX6_RUN_DIR/json/$1 ]
			then
				output="$(cat $BMX6_RUN_DIR/json/$1)"
			fi
		fi
		if [ -z "$output" ]
		then
			output="[]"
		fi
		# BMX6 don't create array for one element.
		# TODO: check if new versions of bmx6 create array for one element.
		if ! echo "$output" | grep -q "^\({ \"$1\": \|\)\[.*\]\( }\|\)$"
		then
			output="[ $output ]"
		fi
		if ! echo "$output" | grep -q "^{ \"$1\": "
		then
			output="{ \"$1\": $output }"
		fi
		echo $output | sed -e "s/{\(.*\)}/\1/g"
	else
		if [ "$id" = "$globalId" ]
		then
			if [ -s $BMX6_RUN_DIR/sms/sendSms/$1 ]
			then
				cat $BMX6_RUN_DIR/sms/sendSms/$1 | sed -e "s/{\(.*\)}/\1/g" \
				&& logger -t $(basename $0) "data from $BMX6_RUN_DIR/sms/sendSms/$1"
			else
				if [ -s $BMX6_RUN_DIR/sms/sendSms/$1.gz ]
				then
					zcat $BMX6_RUN_DIR/sms/sendSms/$1.gz | sed -e "s/{\(.*\)}/\1/g" \
					&& logger -t $(basename $0) "data from $BMX6_RUN_DIR/sms/sendSms/$1.gz"
				else
					b6m_spread_http_json $id $1 | sed -e "s/{\(.*\)}/\1/g"
				fi
			fi
		else
			if [ -s $BMX6_RUN_DIR/sms/rcvdSms/$id\:$1 ]
			then
				cat $BMX6_RUN_DIR/sms/rcvdSms/$id\:$1 | sed -e "s/{\(.*\)}/\1/g" \
				&& logger -t $(basename $0) "data from $BMX6_RUN_DIR/sms/rcvdSms/$id\:$1"
			else
				if [ -s $BMX6_RUN_DIR/sms/rcvdSms/$id\:$1.gz ]
				then
					zcat $BMX6_RUN_DIR/sms/rcvdSms/$id\:$1.gz | sed -e "s/{\(.*\)}/\1/g" \
					&& logger -t $(basename $0) "data from $BMX6_RUN_DIR/sms/rcvdSms/$id\:$1.gz"
				else
					b6m_spread_http_json "$id" "$1" | sed -e "s/{\(.*\)}/\1/g"
				fi
			fi
		fi
	fi
}

b6m_json()
{
	#globalId="$(bmx6 -c --status | grep -v " ERROR " | sed -n 3p | tr -s " " | cut -d" " -f4)"
	globalId="$(cat $BMX6_RUN_DIR/json/status | sed -n -e 's/{ "status": { .*"globalId": "\([^"]*\)".* } }/\1/gp')"
	if [ -z "$globalId" ]
	then
		logger -t $(basename $0) "ERROR: globalId not found, abort."
		return 1
	fi

	if [ -n "$configure" -a -n "$latitude" -a -n "$longitude" ]
	then
		if [ "$configure" = "$globalId" ]
		then
			touch /etc/config/b6m-spread \
			&& uci -q set b6m-spread.geoposition=latlon \
			&& uci -q set b6m-spread.geoposition.latitude="$latitude" \
			&& uci -q set b6m-spread.geoposition.longitude="$longitude" \
			&& uci -q commit b6m-spread \
			&& echo "{ \"saved\": { \"globalId\": \"$globalId\", \"latitude\": \"$latitude\", \"longitude\": \"$longitude\" } }"
		else
			if [ -s $BMX6_RUN_DIR/json/originators/$configure ]
			then
				local primaryIp="$(cat $BMX6_RUN_DIR/json/originators/$configure | sed -n -e 's/{ "globalId": "'$configure'", .*"primaryIp": "\([^"]*\)".* }/\1/gp')"
				if [ -z "$primaryIp" ]
				then
					logger -t $(basename $0) "no primaryIp for $configure"
				else
					$WGET "http://[$primaryIp]/cgi-bin/$(basename $0)?$QUERY_STRING" \
					&& logger -t $(basename $0) "sent configuration to $configure"
				fi
			fi
		fi
	fi

	if [ -z "$get" ]
	then
		logger -t $(basename $0) initial request
		for id in $(ls "$BMX6_RUN_DIR/json/originators/")
		do
			get="$get+$id:originators,descriptions,b6mGeoposition,b6mLinks"
		done
	fi

	local output=""
	for item in $(echo $get | sed -e "s/+/ /g")
	do
		id="$(echo $item | cut -d: -f1)"
		if [ -n "$id" ]
		then
			logger -t $(basename $0) "requested id: $id"

			local actions="$(echo $item | cut -d: -f2)"

			if ! [ -f "$BMX6_RUN_DIR/json/originators/$id" ]
			then
				id="$globalId" \
				&& logger -t $(basename $0) "requested id overwrited: $id"
			fi

			local data=""
			for action in $(echo $actions | sed -e "s/,/ /g")
			do
				local temp_data="$(bmx6_json $action)"
				if [ -n "$temp_data" ]
				then
					[ -n "$data" ] && data="$data, "
					data="$data$temp_data"
				fi
			done
			local outputLength="$(echo "$callback( { $output, \"$id\": { $data } } )" | wc -c)"
			logger -t $(basename $0) "data length: $outputLength"
			if [ "$MAX_LENGTH_OUTPUT" -lt "$outputLength" ]
			then
				logger -t $(basename $0) "data length greater than $MAX_LENGTH_OUTPUT, truncated"
				break
			fi
			[ -n "$output" ] && output="$output, "
			output="$output\"$id\": { $data }"
		fi
	done
	echo "{ $output }"
}

parse_query(){
#@ USAGE: parse_query var ...
# Copyright (C) 2007 Chris F.A. Johnson
    local var val
    local IFS='&'
    vars="&$*&"
    if [ "$REQUEST_METHOD" = "POST" ]
    then
      read post
      QUERY_STRING="$QUERY_STRING&$post"
    fi
    set -f
    for item in $QUERY_STRING; do
      var=${item%%=*}
      val=${item#*=}
      val=${val//+/ }
      case $vars in
          *"&$var&"* )
              case $val in
                  *%[0-9a-fA-F][0-9a-fA-F]*)
                       ## Next line requires bash 3.1 or later
                       #printf -v val "%b" "${val//\%/\\x}."
                       ## Older bash, use: val=$( printf "%b" "${val//\%/\\x}." )
                       # In ash use:
                       val="$(printf "${val//\%/\\x}.")"
                       val=${val%.}
              esac
              eval "$var=\$val"
              ;;
      esac
    done
    set +f
}

parse_query callback id get configure latitude longitude

#callback="$(echo $QUERY_STRING | sed -e "s/callback=\([^&]*\)&.*/\1/g")"
#id="$(echo $QUERY_STRING | sed -e "s/.*&ip=\([^&]*\)&.*/\1/g")"

nodeinfo=$(b6m_json)

# Print information if it don't have any error.

if [ -z "$nodeinfo" ]
then
	logger -t $(basename $0) "no info (503)"
	echo "Status: 503 Service Temporarily Unavailable"
	echo ""
	exit
fi

if ! echo $nodeinfo | grep -q "^$callback(.*)"
then
	nodeinfo="$callback($nodeinfo)"
fi

echo -en "Content-Type: application/javascript\r\n\r\n$nodeinfo"
