#!/bin/sh

PROGNAME="$0"
LT=$HOME/.linuxtrade
PROFDIR=$LT/profiles

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

	Print the stock profile for symbol.  Get a fresh profile if the
	current profile is more than 1 week old.

Options:
	-f	Force refresh of profile
	-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
FORCE=0
unset OPTIND
while getopts "fD:h?" opt
do
	case $opt in
	f)	FORCE=1;;
	D)	DEBUG="$OPTARG";;
	h|\?)	usage;;
	esac
done
shift `expr $OPTIND - 1`

if [ $# = 0 ]; then
    usage
fi

#
#	Main Program
#

# Make directory for profiles
[ -d $PROFDIR ] || mkdir $PROFDIR || error "Can't make $PROFDIR"

# Remove any really old profiles
find $PROFDIR -type f -mtime +14 -exec rm -f '{}' ';'

symbol=`echo "$1" | tr '[A-Z]' '[a-z]'`
s=`expr substr $symbol 1 1`

FILE=$PROFDIR/$s/$symbol.html

TIMESTAMP=$PROFDIR/timestamp
trap "rm -f $TIMESTAMP" 0
# touch -d "yesterday" $TIMESTAMP
touch -d "last week" $TIMESTAMP

if [ $FORCE = 1 -o ! -s $FILE -o $FILE -ot $TIMESTAMP ]; then
    [ -d $PROFDIR/$s ] || mkdir $PROFDIR/$s
    URL="http://biz.yahoo.com/p/$s/$symbol.html"
    lynx -width=99999 -dump -connect_timeout=10 "$URL" > $FILE
fi
cat $FILE
