#!/usr/bin/env python

import sys, os, os.path
import warnings

warnings.simplefilter("ignore", RuntimeWarning)

def usage():
	print "This utility will create a tbz archive containing specified files,"
	print "optimizing for speed and compression ratio wherever it can."
	print
	print "usage: %s archive_name filespec [filespec...]" % sys.argv[0]

if len(sys.argv) < 3:
	usage()
	sys.exit(1)

aname = sys.argv[1]
all_files = []

for spec in sys.argv[2:]:
	if not os.path.exists(spec):
		raise Exception("Not found: "+spec)
	if os.path.isdir(spec):
		for root, dirs, files in os.walk(spec):
			for f in files:
				all_files.append(os.path.join(root, f))
	else:
		all_files.append(spec)


def ext_sort(a, b):
	dummy, a_ext = os.path.splitext(a)
	dummy, b_ext = os.path.splitext(b)
	if a_ext < b_ext:
		return -1
	elif a_ext > b_ext:
		return 1
	else:
		return 0

all_files.sort(ext_sort)

flistf = os.tmpnam()
f = file(flistf, "w")
for file in all_files:
	f.write("%s\n" % file)
f.close()

if os.path.exists("/usr/local/bin/pbzip2"):
	bzip2 = "/usr/local/bin/pbzip2 -c -"
else:
	bzip2 = "bzip2"

os.system("tar -c -T %s -f - | %s > %s" % (flistf, bzip2, aname))

os.unlink(flistf)
