#!/bin/sh
# reinhard@finalmedia.de
# So 29. Sep 10:28:49 CEST 2024
tokendir="/etc/apitokens/"
test -d "${tokendir}" || exit 1
token="$(printenv REQUEST_URI | head -c 256 | grep / | rev | cut -d/ -f3 | rev | tr -dc "0-9a-f")"
test -n "${token}" || exit 2
subfolder="$(printenv REQUEST_URI | head -c 256 | grep / | rev | cut -d/ -f2 | rev | tr -dc "0-9a-zA-ZöäüÖÄÜß.,= _+-")"
folder="${tokendir}/${token}/${subfolder}/cur"
test "${subfolder}" = "cur" && folder="${tokendir}/${token}/${subfolder}"
test "${subfolder}" = "api" && folder="${tokendir}/${token}/${subfolder}"
test -z "${subfolder}" && folder="${tokendir}/${token}/"
filename="$(printenv REQUEST_URI | head -c 256 | grep / | rev | cut -d/ -f1 | rev | tr -dc "0-9a-zA-ZöäüÖÄÜß.,= _+-")"
test -d "${folder}" || exit 3
search="${filename}:*"
search="${filename}*"
test -n "${filename}" && echo "Content-type: text/plain\n" && find "${folder}" -mindepth 1 -maxdepth 1 -type f -name "${search}" -exec cat "{}" \; 2>/dev/null
test -n "${filename}" && exit 0
echo "Content-type: application/json\n"
echo '['
echo '["size","ctime","atime","mtime","name"]'
find "${folder}" -mindepth 1 -maxdepth 1 -type f,d \( -name "api" -o -name "cur" -o -name "new" -o -name ".*" -o -name '[0-9]*' \) -printf ',["%s","%CY%Cm%Cd%CH%CM","%AY%Am%Ad%AH%AM","%TY%Tm%Td%TH%TM","%f"]\n'
echo "]"
exit 0
