#!/usr/bin/env python

import os, sys, re



def mySys(cmd):
	print "os.system('%s')" % (cmd)
	return os.system(cmd)


def getenv(varName, alternate = ""):
	v = os.getenv(varName)

	if v:
		return v
	else:
		return alternate


SSW = getenv("SSW", "/ssw")
home = getenv("HOME", "~")
origPath = getenv("PATH", "/usr/local/bin:/usr/local/qtcoffee/bin:/usr/bin:/bin")
os.environ["PATH"] = "%s/bin:%s/packages/panorama/binaries:/usr/local/bin:/usr/local/qtcoffee/bin:%s" % (home, SSW, origPath)
WATERMARK_FILE = os.path.join(SSW, "packages/panorama/images/aia_watermark_30pct.png")



def getDimensions(movieFile):
	p = os.popen("qt_info %s | fgrep \"movie natural bounds\"" % (movieFile), "r")

	if not p:
		return (-1, -1)

	line = p.readline()
	p.close()
	t = re.sub('\).*$', '', re.sub(r'^.*:\s+\(', '', line.strip()))
	d = t.split(",")
	width = int(d[2]) - int(d[0])
	height = int(d[3]) - int(d[1])
	return (width, height)



def watermark_movie(movieFile, watermarkFile = WATERMARK_FILE):
	(movieWidth, movieHeight) = getDimensions(movieFile)
	(wmarkWidth, wmarkHeight) = getDimensions(watermarkFile)
	#(offsetX, offsetY) = (movieWidth - wmarkWidth - 5, movieHeight - wmarkHeight - 5)
	(offsetX, offsetY) = (movieWidth - wmarkWidth - 10, movieHeight - wmarkHeight - 10)
	tmpMovie = "/tmp/tmp-%d.mov" % (os.getpid())
	#muxmovie orig_720p.mov aia_30a.png -transparency-mode straight-alpha -htranslate 980 -vtranslate 620 -scaleMovieToLengthOfMovie orig_720p.mov -self-contained -o a30.mov
	mySys("nice muxmovie %s %s -transparency-mode straight-alpha -htranslate %d -vtranslate %d -scaleMovieToLengthOfMovie %s -self-contained -o %s" % (movieFile, watermarkFile, offsetX, offsetY, movieFile, tmpMovie))
	mySys("mv -f %s %s" % (tmpMovie, movieFile))




if __name__ == "__main__":
	for f in sys.argv[1:]:
		watermark_movie(f)

