#!/usr/bin/env python
# Converts svg icon theme to png one using inkscape or rsvg

import os.path
import os
import sys
import stat

inkscape_path = None
rsvg_path     = None

SIZES = ["16x16", "22x22", "32x32", "48x48", "64x64", "128x128"]

def find_converter(name):
	env_list = os.environ["PATH"].split(":")

	for i in env_list:
		path = "%s/%s" % (i, name)
		if os.access(path, os.F_OK) and os.access(path, os.X_OK):
			return path
	return None

def convert_ext(name):
	if name[-4:] == ".svg":
		return name.replace(".svg", ".png")
	else:
		return name

def dir_exists(path):
	# first use this since stat() scream if not exists
	if not os.access(path, os.F_OK):
		return False
	mode = os.stat(path)[stat.ST_MODE]
	return stat.S_ISDIR(mode)

def in_subdir(path):
	all = path.split("/")[1:]
	return len(all)

# transform 'foo/XX/yy' to 'dest/sz/yy'
def transform_path(path, dest, sz):
	all = path.split("/")

	# this means we got 'theme/scalable' but we want 'theme/scalable/something/'
	if len(all) < 3:
		return None

	all[0] = dest
	all[1] = sz
	return "/".join(all)

def visit(destdir, dirname, names):
	cmd = None

	# os.walk will first walk on the top of source directory before 
	# enters it's childs; we are interested only in childs
	if not in_subdir(dirname):
		return

	for name in names:
		for sz in SIZES:
			w, h = sz.split("x")

			finaldir = transform_path(dirname, destdir, sz)	
			if finaldir == None:
				continue

			srcicon = "%s/%s" % (dirname, name)
			dsticon = "%s/%s" % (finaldir, convert_ext(name))

			# make it once without exception
			if not dir_exists(finaldir):
				os.makedirs(finaldir)

			if inkscape_path:
				cmd = "%s -e %s -w %s -h %s %s" % (inkscape_path, dsticon, w, h, srcicon)
			elif rsvg_path:
				cmd = "%s -w %s -h %s %s %s" % (rsvg_path, w, h, srcicon, dsticon)

			print "%s -> %s" % (srcicon, dsticon)
			if os.system(cmd) != 0:
				print "FAILED :("

def convert(srcdir, dstdir):
	os.path.walk(srcdir, visit, dstdir) 

def help():
	print "Usage: icon-theme-convert [source] [dest]"
	print ""
	print "Convert [source] icon theme (assumed all files are in SVG format)"
	print "to PNG equivalent one, using rsvg or inkscape. Converted content will be stored in [source]."
	print "If [dest] was given, converted content will be stored there."

def main():
	arg_len = len(sys.argv)
	
	if not arg_len in [2, 3]:
		help()
		return

	# mark them as global
	global inkscape_path
	global rsvg_path

	cpath = find_converter("inkscape")
	if cpath:
		inkscape_path = cpath
	else:
		cpath = find_converter("rsvg")
		if cpath:
			rsvg_path = cpath
		else:
			print "\nUnable to find either inkscape or rsvg. If you have installed"
			print "one of them, append it's directory path to PATH environment.\n"
			print "But if you don't have installed neither of them... well..."
			print "you know what to do then :P\n"
			return

	src = sys.argv[1]

	if arg_len == 3:
		dst = sys.argv[2]
	else:
		dst = src

	if not dir_exists(src):
		print "%s does not exists. Then what to convert?" % src
		return

	convert(src, dst)

if __name__ == "__main__":
	main()