#!/bin/bash

#
# NAME
#	file/dir
#
# SYNOPSIS
#
# DESCRIPTION
#	This function returns a machine readable version of a
#	directory listing in a JSON format required by the SDK
#	PageBuilder.
#
# RETURNS
#	Directory listing
#
# VERSION
#	1.0	2016-06-13	Initial release
#	1.1	2016-07-27	Fix for dir of an empty directory.  Used to return "*"
#	1.2	2017-06-26	Make sdk/file/dir relative to /home
#
LOG=/tmp/sdk.log
application="sdk/file/dir"

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

echo "Content-type: text/plain"
echo "Access-Control-Allow-Origin: *"
echo ""
path=${path#/}
echo "$application: I need to show the directory for path '/home/$path'" >>$LOG
#
# First, make sure the /home/sdk/files/$path is a directory.
#
# For all files in /home/sdk/files/$path
if [ -d "/home/$path" ] ; then
  cd "/home/$path"
  echo -n "  ["
  echo -n "  [" >>$LOG
  numfiles=`ls | wc -w`
  if [ $numfiles -gt 0 ] ; then
    numfiles=0
    for dir in *; do
      if [ $numfiles -gt 0 ] ; then
        echo -n ", "
        echo -n ", " >>$LOG
      fi
      let "numfiles++"
      echo -n " \"$dir\""
      echo -n " \"$dir\"" >>$LOG
    done
  fi
  echo "  ]"
  echo "  ]" >>$LOG
else
  #
  # What should I show if the directory doesn't exist?
  #
  echo "[  ]"
  echo "directory doesn't exist, so return the following" >>$LOG
  echo "[  ]" >>$LOG
fi

exit

