#!/bin/bash

#
# If you're reading this over the web in a browser, it might make more sense if you
# download and view it in a unix friendly text editor.  This is so because there are
# a few ^M characters in this file which most browsers translate into a newline.
#
# This script is used on my planet: http://bluesmoon.info/planet/
#
# See http://tech.bluesmoon.info/2009/11/favicons-on-my-planets-blogroll.html for full description
#

file=$1
if [ -z "$file" ]; then
	echo "Usage: $0 <url file>"
	exit
fi

[ ! -d icons/ ] && mkdir icons/


for feedurl in `sed -ne '/\[http/{s/[][]//g;p;}' $file`; do
	[ -f "$icons/$name" ] && rm "icons/$name"

	echo "[$feedurl]"
	url=$( curl -m 10 -L $feedurl 2>/dev/null | perl -ne "s/></>\\n</g; for (split/\\n/) { print \"\$1\\n\" and exit if /<link/ && (/<link>(.*?)<\\/link>/ || (/text\\/html/ && /alternate/ && /href=['\"](.*?)['\"]/)); }" )
	echo " => $url"
	base=${url%/*}
	domain=`echo $url | sed -e 's,\(https*://[^/]*/\).*,\1,'`
	favicon=$( curl -m 10 -L "$url" 2>/dev/null | perl -ne "print \"\$1\\n\" and exit if /<link/ && /rel=['\"](?:shortcut )?icon['\"]/ && /href=['\"](.*?)['\"]/;" )
	echo " => $favicon"
	if [ -z "$favicon" ]; then
		favicon=$domain/favicon.ico
	else
		favicon=`echo $favicon | sed -e "/^\//{s,^,$domain,;q;}; /^http/q; s,^,$base\/,;"`
	fi
	favicon=$( echo $favicon | sed -e 's,\([^:/]\)//*,\1/,g' )
	echo " => $favicon"
	name=`echo $domain | sed -e 's,/,-,g'`.ico
	params=`curl -m 10 -L -f -w "%{content_type}\t%{size_download}" -o "icons/$name" "$favicon" 2>/dev/null`
	[ $? -ne 0 ] && continue
	ctype=${params%	*}
	clen=${params#*	}
	[ $clen -eq 0 ]  && continue;
	if ! echo $ctype | grep -q "^image/" &>/dev/null; then
		if file -b "icons/$name" | grep '\<text\>' &>/dev/null; then
	       	       continue;
		fi
	fi

	rm "icons/$name"

	perl -pi -e "BEGIN {\$/='';} if(m{^\[$feedurl\]}) { s{^icon =.*$}{}m; s{\n\n$}{\nicon = $favicon\n\n}; }" $file
done


