#! /bin/bash

# set default location
DEFLOC="brno"

# help
USAGE="USAGE
     $(basename "$0") from to [-h -f] [-t -v -w -a] -- simple lynxish version of IDOS (http://jizdnirady.idnes.cz)

OPTIONS:
    -h           show this help text
    -f           show types of transport
    -w [string]  set type of transport or city (see -f)
    -t [string]  set time of either departure or arrival (see -a)
    -v [string]  set via point
    -a           set time is time of arrival

EXAMPLES:
    sheldos loosova otakara+sevcika
    sheldos brno ceske+budejovice -w vlaky -t 1000 -v praha
    sheldos kovarna \"poliklinika sever\" -w ceskebudejovice -t 1900

TYPES OF TRANSPORT
    see -f

NOTES
    You can set the default type of transport in the script by changing the variable DEFLOC.

"

# search by arrival/departure time switch
BYARR="false"

# get stations from and to
FROM=$1
shift
TO=$1
shift

# check if the stations arent blank, if they are, show error, help and exit with exit code 1
# TODO: find out, why this has to be above the argument parsing
if [ -z $FROM ] || [ -z $TO ]; then printf "Starting and/or destination stations must not be blank.\n-----------------\n${USAGE}"; exit 1; fi

# parse arguments
OPTS="t:v:w:fha"
while getopts "$OPTS" OPT; do
	case $OPT in
		t)
			TIME=$OPTARG
			;;
		v)
			VIA=$OPTARG
			;;
		w)
			WHERE=$OPTARG
			;;
		a)
			BYARR="true"
			;;
		h)
			printf "$USAGE"
			exit
			;;
		f)
			less $( dirname "$SOURCE" )/sheldos_data/sheldos_transport_types.txt
			exit
			;;
		\?)
			echo "No such switch"
			exit 1
			;;
		:)
			echo "switch -$OPTARG requires an argument."
			exit 1
			;;
	esac
done

# if type of transport is blank, fallback to default
if [ -z $WHERE ]; then WHERE=${DEFLOC}; fi

# print the generated URL
echo "http://jizdnirady.idnes.cz/${WHERE}/spojeni/?f=${FROM}&t=${TO}&v=${VIA}&time=${TIME}&byarr=${BYARR}&submit=true"

# dump it with linx to temp file
lynx -dump -source -force_html -accept_all_cookies "http://jizdnirady.idnes.cz/${WHERE}/spojeni/?f=${FROM}&t=${TO}&v=${VIA}&time=${TIME}&byarr=${BYARR}&submit=true" > /tmp/sheldos.html

# cut out the actual results, leaving out the trash around which is useless in lynx anyway, because it requires Javascript
sed -n '/<!-- zobrazeni vysledku start -->/,/<!-- zobrazeni vysledku end-->/p' /tmp/sheldos.html > /tmp/sheldos_cut.html

# check if there are any results, if not, ask user whether he wants to see the returned page anyway
if ! [ -s /tmp/sheldos_cut.html ]; then 
	echo "There are no results, do you want to display the page anyway?"
	select yn in "Yes" "No"; do
	    case $yn in
	        Yes ) lynx file:///tmp/sheldos.html; exit;;
	        No ) exit 1;;
	    esac
	done
fi

# view the temp file in lynx
lynx file:///tmp/sheldos_cut.html