#!/bin/bash -r

# Standard converter script for Gopher menu generated by currencyconv.sh
# Supplied with currencyconv.sh by The Free Thinker, 2020.
# V. 1, R. 1
#
# Reads CGI $QUERY_STRING environment variable in format:
#  [AMOUNT][IN CURRENCY CODE]
# or:
#  [AMOUNT] [IN CURRENCY CODE]
#
#Note: Runs restricted for security (bash -r parameter)

# Set this to the currency menu gophermap directory as shown in the Gopher path:
CONVROOT="/~freet/currconv"

# Location of the file where Units currency data is (uses default if not set):
export UNITSFILE="/home/freet/goph/currconv/currency.units"

CUSTOMCURR="`cat ../customcurr.csv`"
CONVAMOUNT="`expr "$QUERY_STRING" : '\([0-9]\+\|[0-9]*\.[0-9]\+\)[[:blank:]a-zA-Z]*'`"
CONVINCODE="`expr "$QUERY_STRING" : '[0-9.]\+[[:blank:]]*\([a-zA-Z]\{3\}\)' | tr '[:lower:]' '[:upper:]'`"
[ -z "$CONVOUTCODE" ] && CONVOUTCODE="`expr "$PWD" : '.*/\([A-Z]\{3\}\)$'`"

CUSTOMCODE="`expr \"$CUSTOMCURR\" : \"$CONVINCODE,.*,\([a-z]*\)\"`"
[ "$CUSTOMCODE" ] && CONVINCODE=$CUSTOMCODE

CUSTOMCODE="`expr \"$CUSTOMCURR\" : \"$CONVOUTCODE,.*,\([a-z]*\)\"`"
[ "$CUSTOMCODE" ] && CONVOUTCODE=$CUSTOMCODE

if [ "$CONVINCODE" ] && [ "$CONVAMOUNT" ]
then
cat head.txt
echo -n "$CONVAMOUNT$CONVINCODE is:          "
units -t -o %.4f  "$CONVAMOUNT$CONVINCODE" "$CONVOUTCODE"
[ $? -ne 0 ] && echo -e "Invalid input amount/currency.\nUsage is: [Amount][3-Letter Currency Code]"
echo -e "\n1More conversions where that came from...\t$CONVROOT"
else
echo -e " No idea what you're asking for there.\n\
What I'm looking for is: [Amount][3-Letter Currency Code]\n\
eg. 28.61GBP\n\n\
1Give it another try\t$CONVROOT"
fi