#!/usr/local/bin/rc
# Created by IanJ 2025 and released into the public domain without warranty or restriction.
# Use it at your peril!

##### For IFS #####
tab='   '; nl='
'
###################
SERVER_NAME  =gopher.icu
SERVER_PORT  =70
SERVER_ROOT  =/var/gopher
LOG_FILE     =/var/log/gophrc.log
INDEX_FILE   =index.dcgi

client_info=``(! $nl){fstat -p $pid | grep stream | head -1 | \
       sed -E 's/\[|\]//g;s/.*<-- (.*):(.*)$/\1!\2/'}
REMOTE_ADDR=$client_info(1)
REMOTE_PORT=$client_info(2)

fn log_request {
       printf '[%s|%s|%s|%s] %s\n' ``($nl){date +'%Y-%m-%d %H:%M:%S %z'} $REMOTE_ADDR $REMOTE_PORT $1 $2 >> $LOG_FILE
}

fn unf_geomyidae {
       echo $* | awk -v 'server='$SERVER_NAME -v 'port='$SERVER_PORT \
       '{
               if (/^\[.*\|.*\|.*\|.*\]$/) {
                       gsub(/^\[|\]$/, ""); split($0, a, "|")
                       gsub("server", server, a[4])
                       gsub("port", port, a[5])
                       printf("%s%s\t%s\t%s\t%d\r\n", a[1], a[2], a[3], a[4], a[5])
               } else {
                       printf("i%s\t%s\t%s\t%d\r\n", $0, "info", server, port)
               }
       }'
       printf '.\r\n'
}

# Unused convenience function to convert none gopher type lines to type 'i'.
#
# Unlike the above function it leaves you to format menu manually, barring
# the single dot on the last line of output.
#
# Can be used in place of 'echo -n' below.
fn convenience {
       echo $* | awk -v 'server='$SERVER_NAME -v 'port='$SERVER_PORT \
       '{
               if (!/^([0-9]{1}|\+|g|I|T|d|h|i|p|r|s|P|X)/) {
                       printf("i%s\t%s\t%s\t%d\r\n", $0, "info", server, port)
               } else {
                       print
               }
       }'
       printf '.\r\n'
}

fn read {
       $1=``($tab){awk '{print;exit}' | tr -d '\r\n;\\' | sed -E 's!\.{2}!!g' }
}

read selector
qrs=``(? $nl){echo $selector(1)} ## split path and parameters

cd $SERVER_ROOT
doc=$SERVER_ROOT/$qrs(1)

if(test -d $doc){
       cd $doc
       doc=$doc/$INDEX_FILE
}

stat = serving
if(test -e $doc){
       switch($doc){
               case *.dcgi
                       unf_geomyidae ``(){exec $doc $selector(2)^'' $qrs(2)^'' $REMOTE_ADDR^'' $REMOTE_PORT^''}&
               case *.cgi
                       echo -n ``(){exec $doc $selector(2)^'' $qrs(2)^''}&
               case *
                       cat $doc
       }
} else {
       stat='not found'
       nd=`{echo $doc | sed -E s!$SERVER_ROOT!! }
       printf '3"'$nd'" not found.     err.selector    err.host        err.port\r\n.\r\n'
}

log_request $^stat $^selector