#!/usr/bin/python
# Written by Aaron Isotton <aaron@isotton.com>
# Released under the MIT license.

import sys, os

def run(favdir, outfile, level=1):
    if (level == 1):
	print >> outfile, '<!DOCTYPE NETSCAPE-Bookmark-file-1>'
	print >> outfile, '<META HTTP-EQUIV="Content-Type" ' \
		'CONTENT="text/html; charset=UTF-8">'
	print >> outfile, '<H1>Bookmarks</H1>'
    for entry in os.listdir(favdir):
	if entry[0] == '.': continue
	abspath = os.path.join(favdir, entry)
	if os.path.isdir(abspath): 
	    # subdir
	    title = entry.encode('utf-8')
	    print >> outfile, '<DT><H%d>%s</H%d>' % (level+1, title, level+1)
	    print >> outfile, '<DL>'
	    run(abspath, outfile, level+1)
	    print >> outfile, '</DL>'
	elif entry.endswith('.url') and os.path.isfile(abspath):
	    # this is a bookmark
	    title = entry[:-4].decode('utf-8').encode('utf-8')
	    fp = open(abspath, 'r')
	    url = None
	    for line in fp.readlines():
		if line.startswith('URL='): url = line[4:]
	    if url is not None:
		print >> outfile, '<DT><A HREF="%s">%s</A>' % (url, title)


def main():
    if len(sys.argv) != 3:
	print >> sys.stderr, 'Usage: fav2html FAVDIR HTMLFILE'
	sys.exit(1)

    favdir = sys.argv[1]
    outfile = sys.argv[2]

    run(favdir, open(outfile, 'w'))

if __name__ == '__main__': main()

