#!/bin/sh

tmpfile="$(mktemp)"
spirometrydb="/home/david/share/spirometry"

datetime="$(date +%Y-%m-%d-%H-%M-%S)"
if [ $# -gt 0 ];
then
	infile="$1"
	case "${infile}" in
	/dev/rfcomm*)
		stty -F "${infile}" raw -echo -echoe -echok
		;;
	*)
		datetime="$(echo $infile \
			| cut -d- -f 2- \
			| cut -d'.' -f 1)"
		;;
	esac
else
	infile="/dev/stdin"
fi

cat "${infile}" > "${tmpfile}"
dbpath="${spirometrydb}"
cd "${dbpath}"
outfile="spirometry-$(cat "${tmpfile}" \
	| tr -d '\r' \
	| iconv -f iso8859-1 -t utf-8 \
	| grep -a "^NAME" \
	| sed 's,NAME \([^ ]*\)[ ]*\([^ ]*\)[ ]*#ID \([0-9]*\)[ ]*,\1-\2-\3,' \
	| sed 's, ,_,g; s,/,_,g;')-${datetime}.pcl"
mv "${tmpfile}" "${outfile}" 2>/dev/null
chown david:david "${outfile}" 2>/dev/null

cat "${outfile}" \
	| sed '/Daten von spirolab III Ver/d'  \
	| lpr

