#!/bin/sh
# Copyright 2020 Haelwenn (lanodan) Monnier <contact+gemini@hacktivis.me>
# Distributed under the terms of the GNU Affero General Public License version 3

# AGPL-3 because it's a service on the internet, screw permissive licences for these

export GEMDIR="/srv/gemini"

IFS=#'
' read -r line
# ' hack for vis editor to reset hightlighting…

query="${line#gemini://*/}"
query="${query%%../*}"
query="${query//%20/ }"
path="$GEMDIR/${query:-index.gmi}"
status="--"

if echo $path | egrep -q '.gmi$'
then
	mime="text/gemini; charset=utf-8"
else
	mime=$(file --mime -b "$path" 2>/dev/null)
fi

if [ -r "$path" -a -f "$path" ]
then
	status="20"
	printf '20 %s\r\n' "$mime"
	cat "$path" 2>/dev/null
elif [ -r "$path" -a -d "$path" ]
then
	if echo $path | egrep -q '/$'
	then
		status="20"
		printf '20 text/gemini; charset=utf-8\r\n'
		printf '# Index of %s\n' "$query"
		ls "${path}" | sed -e 's/ /%20/g' -e "s/^/=> /" 2>/dev/null
	else
		status="30"
		printf '30 /%s/\r\n' "$query"
	fi
else
	status="50"
	printf '50 File not readable or non-existent\r\n'
fi

# I know… blame France data rentention policy
logger -p local0.notice "${REMOTE_HOST:-?host?}	${REMOTE_PORT:-?port?}	${line} ${status}" 2>/dev/null 1>/dev/null