#!/bin/sh
TDIR=$HOME/kurs
SDIR=$HOME/public_html
KDIR=$LOGNAME
TO=ml@envs.net
FILEx=$HOME/bin/long
FILE1=$HOME/kursx-`date +%d-%m-%y`.txt
FILE2=$HOME/kursxx-`date +%d-%m-%y`.txt
FILE3=$HOME/lynx_bookmarks.html
LOCK=$HOME/.lock
if [ $# -gt 1 ]; then
	echo "usage: "`basename $0`" [debug]"
	exit 1
fi
date > $LOCK
cd $TDIR
an.sh $FILEx kurs > $FILE1
chmod 700 $FILE1
$FILE1
cd $SDIR
if [ -d $KDIR ]; then
	rm -r $KDIR
fi
mkdir $KDIR
cp $TDIR/*.kurs $KDIR
tar cfz $KDIR.tgz $KDIR
chmod 644 $KDIR.tgz
cd $TDIR
for a in `awk '{print $1}' $FILEx`
do
	if [ -e $a.kurs ]; then
		grep -m 1 -A 1 Geld $a.kurs | grep % | \
		awk '{print $1}' | sed 's/,/./g' > $FILE1
		if [ $# -gt 0 ] && [ $1 = "debug" ]; then
#                if [ -s $FILE1 ]; then
			echo -n $a" "
			cat $FILE1
			rm $FILE1
#		fi
		else
			if [ -s $FILE1 ]; then
				if [ `awk '{printf ("%i",$1)}' \
				$FILE1` -gt 0 ]; then
					if [ -e $a.txt ]; then
						awk '{ORS=" ";print $1}' \
						$FILE1 > $FILE2
						cat $a.txt >> $FILE2
						if [ `awk '{printf \
						("%i",100*($1-$2))}' \
						$FILE2` -lt 0 ]; then
							awk '{print $1}' \
							$FILE2 > $a.txt
							chmod 600 $a.txt
							if [ `grep -c \
							$a $FILE3` = 1 ]; then
								awk '{ORS=" "; \
								print $1}' \
								$a.txt > $a.tmp
								getname.sh \
								$a >> $a.tmp
							else
								cp $a.txt $a.tmp
							fi
							if [ $# -gt 0 ] && \
							[ $1 = "fg" ]; then
								echo -n $a" "
								cat $a.tmp
							else
								mutt -n -F \
								$HOME/.norecord -s \
								"$a-`date +%d-%m-%y`-sold" \
								$TO < $a.tmp
							fi
							rm $a.tmp
						fi
						rm $FILE2
					else
						cp $FILE1 $a.txt
						if [ $# -gt 0 ] && \
						[ $1 = "fg" ]; then
							echo -n $a" "
							cat $a.txt
						fi
					fi
				fi
			fi
			if [ -e $FILE1 ]; then
				rm $FILE1
			fi
		fi
		rm $a.kurs
	fi
done
if [ `date +%H` -gt 9 ]; then
	archive.sh kurs
fi
rm $LOCK
