#! /bin/bash

fidocadj=/usr/local/bin/fidocadj.jar
fp=fidocad-$$				# file name prefix

cd /home/pot/www/potorti.it/pot/fidocad	# go where al the files are

## Read arguments string from CGI
IFS='&=' read -a args			# separate arguments in array
for ((i=0; i<${#args[*]}/2; i++)); do	# read them one by one
    name="${args[$((2*i))]}"		# arg name
    value="${args[$((2*i+1))]}"		# arg value
    case "$name" in
	imgfmt)				# PNG or SVG
	    f=png
	    if [ "$value" = 2 ]; then f=svg; fi
	    ;;
	height)				# pixel height
	    h="${value//[^0-9]}"	# remove non-digits
	    ;;
	width)				# pixel width
	    w="${value//[^0-9]}"	# remove non-digits
	    ;;
	source)				# source to be percent-decoded
	    source="${value//[^%+0-9A-Za-z*~._-]}" # remove reserved characters
	    source="${source//%0[Dd]}"		   # remove carriage returns
	    source="${source//+/ }"		   # decoding spaces
	    echo -e "${source//%/\\x}" > $fp.fcd   # decode percents
	    ;;
    esac
done

LC_CTYPE=en_US.UTF-8 java -jar $fidocadj -n -c "$w" "$h" $f $fp.$f $fp.fcd >$fp.out 2>&1

cat <<EOF
Content-Type: text/html
Connection: close

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
  <TITLE>Damatfrc.m Output</TITLE>
  <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
</HEAD>
<BODY>
  <OBJECT TYPE="image/$f" DATA="/fidocad/$fp.$f" WIDTH="$w" HEIGHT="$h"></OBJECT>
</BODY>
</HTML>
EOF
