#!/bin/sh

#
# Version 0.0.0 May 2016
#
# spd @ daphne.cps.unizar.es
# script to read DRAE
# Requires wget
# Requires perl
# Requires recode
#

# Status: works


#
# Defaults:
#

PATH=/bin:/usr/bin:/bin:/usr/X11R6/bin:/sbin:/usr/sbin:/usr/etc:/usr/local/bin
LD_LIBRARY_PATH=/usr/local/lib
export LD_LIBRARY_PATH
PATH=$PATH:/usr/local/bin/X11
PATH=$PATH:/usr/sfw/bin
PATH=$PATH:/usr/bsd
PATH=$PATH:/opt/csw/bin
export PATH

if [ -f /usr/nekoware/bin/perl ]
then
	PERL=/usr/nekoware/bin/perl
else
	PERL=perl
fi

DEBUG=:
DEBUG=false

AGENT=Mozilla/5.0

SED=sed

if [ -x /usr/local/bin/sed ]
then
	SED=/usr/local/bin/sed
fi

trap "on_exit" 1 2 3 15

TMPHTML=./foo.$$.html
TMPDECO=./foo.d.$$.html
TMPPNG=./foo.$$.png
COOKIES=./cookies.$$.txt
COOK="--keep-session-cookies --save-cookies $COOKIES --load-cookies $COOKIES"
#COOK="--user-agent=Mozilla/5.0 --no-check-certificate $COOK"
UA="Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"

wg()
{
	wget \
	--quiet \
	--user-agent="$UA" \
	--keep-session-cookies \
	--save-cookies $COOKIES \
	--load-cookies $COOKIES \
	-O - \
	$*
}

on_exit()
{
	rm -f $TMPHTML $TMPDECO $TMPPNG $COOKIES
	date
	exit
}

for f in $TMPHTML $TMPDECO $TMPPNG $COOKIES
do
	test -f $f && (echo Please, delete $f first; exit 1)
done
touch $COOKIES


VERBOSE=-nv

#
#

ECHO="echo"
ECHON="echo"

case `uname` in
	OSF*)
		CMD_ENV=bsd; export CMD_ENV
		ECHO="echo -e"
		ECHON="/bin/echo"
		;;
	Darwin*|Linux*)
		ECHO="echo -e"
		ECHON="/bin/echo"
		;;
	*)
		[ -x /usr/ucb/echo ] && ECHO="/usr/ucb/echo"
		ECHON=$ECHO
		;;
esac

SED=sed

if [ -x /usr/local/bin/sed ]
then
	SED=/usr/local/bin/sed
fi


trap "on_exit" 0 1 2 3 15

TMPHTML=./foo.$$.html
TMPRCHTML=./foo-rc.$$.html
TMPPNG=./foo.$$.jpg

on_exit()
{
	rm -f $TMPHTML $TMPRCHTML $TMPPNG
	date
	exit
}

for f in $TMPHTML $TMPRCHTML $TMPPNG
do
	test -f $f && (echo Please, delete $f first; exit 1)
done

URL="$1"

if [ -z "$URL" ]
then
	echo "Please, input URL"
	read URL
fi

if [ -z "$URL" ]
then
	echo use: $0 lema
	exit 1
fi

LEMA=`echo "$URL" | recode iso-8859-1..utf-8 `
LEMA=`$PERL -MURI::Escape -le 'print uri_escape("'$LEMA'")'`

URL="http://dle.rae.es/srv/search?w=$LEMA"

#FILE=`basename $URL|$SED -e 's/\.html//'`

wg http://dle.rae.es  > $TMPHTML
wg --referer=http://dle.rae.es "$URL" > $TMPHTML

if $DEBUG
then
	cp $TMPHTML debug-drae.html
fi


FOUND=false

cat $TMPHTML | awk -F\" '/href.*fetch/ {print $2}' | while read link
do
	FOUND=:
	URLP="http://dle.rae.es/srv/$link"
	wg --referer="$URL" "$URLP"  |\
	w3m -dump -T text/html |\
	cat
	#recode -f UTF-8..ISO-8859-1
done

if $FOUND
then
	:
else
	cat $TMPHTML | \
	w3m -dump -T text/html |\
	cat
	#recode -f UTF-8..ISO-8859-1
fi


on_exit

exit 0

