#!/bin/bash

LOG=/tmp/sdk.log
application="sdk/file/signature"

#
# NAME
#	file/signature
#
# SYNOPSIS
#	file/signature?key=1010101010101010&path=applications/viking/resources/image.png
#
# DESCRIPTION
#	This function returns signature for provided file and key
#
#
# RETURNS
#	
#	<response>
#		<statusCode>0</statusCode>
#		<mac>56721986dbd669d7</mac>
#	</response>
#
#	<response>
#		<statusCode>some error code</statusCode>
#		<error>some error message</error>
#	</response>

#
# VERSION
#	1.0	2017-06-01	Initial release
#	1.0	2017-26-06	Make sdk/file/signature relative to /home
echo "$application: begin" >>$LOG ; sync                          
if [ -z "$QUERY_STRING" ] ; then                                                
  echo "$application: No parameters QUERY_STRING" >>$LOG
else
  echo "$application: QUERY_STRING = '$QUERY_STRING'" >>$LOG
  saveIFS=$IFS
  IFS=\&
  set $QUERY_STRING
  while [ "$1" ] ; do
    left=${1%=*}
    right=${1#*=}
    eval $left=$right
    echo "Parameter '$left' = '$right'" >>$LOG
    shift
  done
  IFS=$saveIFS
fi

RESOURCE_PATH=/home/$path

OUTPUT=$(/home/sdk/bin/mac -t $type -k $key $RESOURCE_PATH -o /dev/null)
STATUS_CODE=$?

echo "Content-type: text/xml"
echo ""
echo '<?xml version="1.0" encoding="iso-8859-1"?>'
echo "<response>"
echo "<statusCode>$STATUS_CODE</statusCode>"
if [ $STATUS_CODE -eq 0 ]; then
	MAC=$(echo "$OUTPUT" | grep -o 'MAC:\s\S*')
	echo "<mac>${MAC:5}</mac>"
else 
	echo "<error>$OUTPUT</error>"
fi  
echo "</response>"