#!/bin/sh

file="$HOME/share/forex.units"
oneday=$((24 * 3600))
now=$(date +%s)
then=$(stat -qf %m "$file") # if file doesn't exist, $then is 0

type curl unzip >/dev/null || {
	echo "${0##/}: make sure curl, unzip and units are installed" >/dev/stderr
	exit 1
}

test $((now - then)) -gt $oneday && {
	curl -s 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref.zip' |
	unzip -p /dev/stdin |
	awk -F ', ' '
	# first field is date, last field is empty
	NR == 1 { for (i=2; i<NF; i++) name[i]=tolower($i) }
	NR == 2 { for (i=2; i<NF; i++) val[i]=$i; exit}
	BEGIN { printf("%s\n%s\n%s\n%s\n",
		"euro	!a!",
		"eur	euro",
		"lei	ron",
		"leu	ron" ) }
	END { for (i=2; i<NF; i++)
		printf("%s\t1|%g eur\n", name[i], val[i]) }
	' > "$file"
}
test -f  "$file" &&  
	units -f "$file" "$@"
