#!/usr/bin/env bash
export LC_ALL=C

# do premennej SITE ulozime iba server
SITE=`echo $1 | sed 's@\(http://[^/]*\).*@\1@'`

# ak neexistuje adresar img, vytvorime ho
# budeme donho ukladat obrazky
if ! -d img
then
	mkdir img
fi

# prechadzame vsetky URL na schranke
for RURL in `
wget -O - -q $1 | 
	tr -d '\n' | 
	sed 's/>/>\n/g' |
	grep '< *[iI][mM][gG].*[sS][rR][cC]'|
	sed 's/.*</</' |
	sed "s/.*[iI][mM][gG].*[sS][rR][cC] *= *[\"']\?//" |
	sed "s/[ \"'].*//"`
do
	URL=$RURL
	
	# vytvorime uplne URL pre wget
	# musime rozlisit typy ^http://, ^/ a ostatne
	if test -z `echo $RURL | grep '^http://'` 
	then
	  if test -z `echo $RURL | grep '^/'`
	  then
		URL=${1}${RURL}
	  else
          	URL=${SITE}${RURL}
	  fi
	fi	
	
	# meno suboru je to, co je za poslednym lomitkom v URL
	FNM=`echo $URL | sed 's@.*/@@'`

	# niektore stranky obsahuju viacej razy ten isty obrazok
	# vtedy ho nestahujeme viac razy, je to zbytocne
	# testujeme tu, ci subor uz existuje
	if test ! -f img/$FNM
	then 
		echo $URL
		wget -O img/$FNM -q $URL
	fi
done


