#!/bin/bash

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

#
# NAME
#	file/get
#
# SYNOPSIS
#	file/get?path=pathToTheFile
#
# DESCRIPTION
#	This function either returns the selected file as
#	a Content-Type: application/octet-stream or
#	returns an error message in Content-type: text.plain
#
# RETURNS
#	response=1	Path name not specified
#	response=2	The requested file was not found
#
# VERSION
#	1.0	2016-06-13	Initial sdk version
#	1.1	2017-06-26	Make sdk/file/get relative to /home
#
echo "" >>$LOG
echo "$application: Begin" >>$LOG

if [ -z "$QUERY_STRING" ] ; then                                                
  echo "$application: No parameters on the command line" >>$LOG
else
  IFS=\&                                                                       
  set $QUERY_STRING                                                             
  while [ "$1" ] ; do
    left=${1%=*}                         
    right=${1#*=}
    eval $left=$right
    echo "$application: Parameter '$left' = '$right'" >>$LOG
    shift                                                     
  done
fi       

if [ -z ${path+x} ] ; then
  #
  # $path not specified.
  #
  echo "Content-type: text/plain"
  echo ""
  echo "response=1"
  exit
fi

path=${path#/}
echo "$application: Looking for file '/home/$path'" >>$LOG
if [[ -f "/home/$path" ]] ; then
  #
  # File exists.  Return it to the caller
  #
  echo "Content-type: application/octet-stream"
  echo ""
  echo "$application: cat /home/$path" >>$LOG
  cat /home/$path
  #cat /home/$path >>$LOG
else
  #
  # File doesn't exist.
  #
  echo "Content-type: text/plain"
  echo ""
  echo "$application: File $path not found" >>$LOG
fi

