#!/bin/sh
#
# b6m-spread http interface
#
# 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/>.
#

DATA_DIR="/tmp/b6m-spread"
BMX6_JSON_DIR="/var/run/bmx6/json"
BMX6_JSON_ORIGINATORS_DIR="$BMX6_JSON_DIR/originators"
PROG_NAME="$(basename $0)"
MY_GLOBALID="$(sed -e 's/^.*"globalId": "\([^"]*\)".*/\1/g' $BMX6_JSON_DIR/status)"

clean()
{
	if [ ! -s "$BMX6_JSON_ORIGINATORS_DIR" ]
	then
		return
	fi

	for globalId in $(ls "$DATA_DIR")
	do
		if [ "$globalId" != "$MY_GLOBALID" -a ! -s "$BMX6_JSON_ORIGINATORS_DIR/$globalId" ]
		then
			rm -r "$DATA_DIR/$globalId" \
			&& logger -t $PROG_NAME "removed $DATA_DIR/$globalId"
		fi
	done
}

[ "$REQUEST_METHOD" = "POST" ] && read QUERY_STRING

action="$(echo "&$QUERY_STRING" | sed -n -e "s/^.*&action=\([^&]*\)&\?.*$/\1/gp")"
globalId="$(echo "&$QUERY_STRING" | sed -n -e "s/^.*&global_id=\([^&]*\)&\?.*/\1/gp")"
dataType="$(echo "&$QUERY_STRING" |  sed -n -e "s/^.*&data_type=\([^&]*\)&\?.*/\1/gp")"

if [ "$action" = "get" ]
then
	if [ -n "$dataType" ]
	then
		echo -en "Content-Type: application/json\r\n\r\n"
		cat $DATA_DIR/$globalId/$dataType
	fi
elif [ "$action" = "set" ]
then
	data="$(echo "&$QUERY_STRING" | sed -n -e "s/^.*&data=\([^&]*\)&\?.*/\1/gp")"

	logger -t $PROG_NAME "data recivied globalId: $globalId dataType: $dataType data: $data"

	if [ -n "$globalId" ] && [ -n "$dataType" ]
	then
		mkdir -p $DATA_DIR/$globalId \
		&& echo "$data" > $DATA_DIR/$globalId/$dataType \
		&& logger -t $PROG_NAME "saved to $DATA_DIR/$globalId/$dataType"
	fi
fi

clean
