#!/bin/bash
#Write for downing special type of file in website.
#Author:cocobear
#E-Mail:cocobearc@gmail.com
URL=false
FILE=false
HELP=false
TYPE=false
function help() {
	echo "Usage:$0 -[f <filename> h u <url> ] -[t type] "
	exit 1;

}
function awkfile() {
	filename="$1.$2"
	#type="$2$" match specify type at the end of url 
	awk -v type="$2$" '
	BEGIN {FS = "\""} 
	{
	for (i=1;i<=NF;i++)
	if (($i ~ /^http:/) && ($i ~ type ))
		{print $i}
	}' $1 > $filename
	echo "Delete temp file."
	rm  $1
	if [ -s $filename ]
	then wget -i $filename
	else echo "Find nothing match $2"
	fi
	echo "Delete temp file."
	exit 0
}
function processurl() {
	tempfile="downfile"
	if [ -e $tempfile ]
	then 
		echo "$tempfile exist!!" 
		exit 1
	fi
	#redirection 
	wget -O $tempfile $1
	if [ -s $tempfile ]
	then awkfile $tempfile $2
	else echo "Nothing down!"
	fi
	exit 0
}

if [ $# -eq 0 ]; 
then
	help
	exit 1 
fi

#deal with option
while getopts :f:hu:t: option
do
case $option in
f)FILE=$OPTARG
;;
h)help
;;
u)URL=$OPTARG
;;
t)TYPE=$OPTARG
;;
?)
echo "Missing arguments!"
help
;;
esac
done
if [ $TYPE = "false" ]
then {
	echo "Missing type"
	help
}
else {
	if [ $FILE = "false" ] && [ $URL = "false" ]
	then {
		echo "Must specify the filename or url"
		help
	}
	else {
		if [ $FILE != "false" ] &&  [ $URL != "false" ]
		then {
			echo "filename and url can't be specify together"
			help
		}
		fi
	}
	fi	
}
fi
#main
if [ $FILE != "false" ]
then {
	if [ -e $FILE ]
	then awkfile $FILE $TYPE 
	else {
		echo "$FILE does not exist!\n"
		exit 1
	}
	fi
} 
else processurl $URL $TYPE
fi


