#!/usr/bin/python
#
# usage: python touch-with-newest.py target-file dirs or files ...
# change atime and mtime to the latest mtime of the files or files in dirs
#
# Copyright (C) 2006 zunda <zunda at freeshell.org>
#
# Permission is granted for copying, modification, distribution,
# and distribution of modified versions of this work under the
# terms of GPL version 2. Read the GPL file for more details.
#

import sys
import os

def mtime_max(root):
	max = os.lstat(root).st_mtime
	for top, dirs, files in os.walk(root):
		for file in (files + dirs):
			mtime = os.lstat(os.path.join(top, file)).st_mtime
			if max < mtime:
				max = mtime
	return max

if __name__ == "__main__":
	cmdname = sys.argv.pop(0)
	if len(sys.argv) < 2:
		sys.exit("Too few command line arguments")
	max = 0
	target = sys.argv.pop(0)
	for file in sys.argv:
		mtime = mtime_max(file)
		if max < mtime:
			max = mtime
	if 0 == max:
		sys.exit("The newest file is too old")
	if not os.access(target, os.W_OK):
		f = open(target, "w")
		f.close
	os.utime(target, (max, max))

