#!/bin/sh

PROGNAME="$0"
PATH=$PATH:$HOME/bin:/usr/share/linuxtrade/bin

usage() {
	cat <<EOF
Usage:
	`basename $PROGNAME` [options]

	Make a list of companies reporting earnings today, and eliminate
	those that do not pass the constraints of lt-stockfilter.  The
	definition of today is modified so that "today" actually starts
	at 8PM the day before.

	NOTE: Uses lt-stockfilter which in turn uses lt-stockprofile.

Options:
	-a		Only stocks reporting earnings after hours
	-b		Only stocks reporting earnings before open
	-d days		Report earnings "days" in the future
	-p price	Override lt-stockfilter's minimum price
	-P price	Override lt-stockfilter's maximum price
	-v volume	Override lt-stockfilter's minimum volume
	-V volume	Override lt-stockfilter's maximum volume
	-D lvl		Debug level
EOF

	exit 1
}

#
#       Report an error and exit
#
error() {
	echo "`basename $PROGNAME`: $1" >&2
	exit 1
}

#
#       Process the options
#
DEBUG=0
VOLmin=
VOLmax=
PRICEmin=
PRICEmax=
TIMEFILT=
DAYS=0
unset OPTIND
while getopts "abd:p:P:v:V:D:h?" opt
do
	case $opt in
	a)	TIMEFILT=AH;;
	b)	TIMEFILT=B4;;
	d)	DAYS="$OPTARG";;
	p)	PRICEmin="-p$OPTARG";;
	P)	PRICEmax="-P$OPTARG";;
	v)	VOLmin="-v$OPTARG";;
	V)	VOLmax="-V$OPTARG";;
	D)	DEBUG="$OPTARG";;
	h|\?)	usage;;
	esac
done
shift `expr $OPTIND - 1`

#
#	Main Program
#

# Figure out what day we should get earnings for.
# Roll over to next day at 8PM
dow=`date -d "now + 4 hours" +"%w"`
case "$dow" in
6) date=`date -d "now + 52 hours + $DAYS days" +"%Y%m%d"` ;;
0) date=`date -d "now + 28 hours + $DAYS days" +"%Y%m%d"` ;;
*) date=`date -d "now + 4 hours + $DAYS days" +"%Y%m%d"` ;;
esac

echo "label=Earnings $date"
# Snarf the earnings calendar page and massage the output
lynx -width=9999999 -dump -connect_timeout=10 \
        "http://biz.yahoo.com/research/earncal/$date.html" \
| grep "]Add" \
| sed \
    -e 's/[[0-9]*]Add.*//' \
    -e 's/.*]//' \
    -e 's/After Market Close/AH/' \
    -e 's/Before Market Open/B4/' \
    -e 's/Time Not Supplied/UNK/' \
| while read sym est time
  do
    case "$TIMEFILT" in
    AH|B4)
	case "$time" in
	$TIMEFILT)	;;
	*)		continue;;
	esac
	;;
    esac
    echo "$sym	$time($est)"
  done  \
| sort -t '	' -k2.1,2.1 -k1,1 \
| lt-stockfilter $PRICEmin $PRICEmax $VOLmin $VOLmax
