# Search through local directories for our given file
# arguments:
# basePath = starting directory

import os
import string
import time
import re
import zipfile

def callback(arg, directory, files):
        """Take a stroll and return a list of directories from the current directory"""
        arg.append(directory)

def searchDir(self, basePath, query):
	#Search for the "query", starting at basePath
	foundPath = ""

	if (query == ""):
		if (os.path.exists(basePath)):
			foundPath = basePath 

	mylist = []
	os.path.walk(basePath, callback, mylist)

	for x in mylist:
        	fileList = [os.path.normcase(f) for f in os.listdir(x)]
        	for y in fileList:
                	if (y == query):
                        	foundPath = x

	return foundPath

def viewArchive(self, archive):
	# expose the contents of an archive

	# Set nativeZip to 0 if your Operating System seems
	# to have trouble dealing with showing Zip archives.
	# This will use the built-in Python method (which
	# has the drawback of not being able to show .zip
	# files with comments, but at least it works!)
	nativeZip = 1 

	#determine what kind've archive we're dealing with
	lastDot = string.rfind(archive, ".")

	if (lastDot > 0):
	  	lastBit = archive[lastDot:len(archive)]
	else:
  		lastBit = ""

	lastBit = string.lower(lastBit)

	# An array to keep our filenames and info in
	fileList = []

	if (lastBit == ".zip" and nativeZip == 0):
		file = zipfile.ZipFile(archive, "r")
		for info in file.infolist():
			d = info.date_time
			tempDate = ""+str(d[0])+"/"+str(d[1])+"/"+str(d[2])+" "+str(d[3])+":"+str(d[4])+":"+str(d[5])+""
			fileList.append("<td>"+info.filename+"</td><td>"+tempDate+"</td><td>"+str(info.file_size)+" bytes</td>")
		return fileList				

	if (lastBit == ".gz" or lastBit == ".tgz" or lastBit == ".tar" or lastBit == ".zip"):
		# Check the contents of a tar file.  We have to do this
		# Manually and read from stdout
		if (lastBit == ".tar"):
			cmdIn, cmdOut = os.popen4("tar tvf "+archive)
		elif (lastBit == ".zip"):
			cmdIn, cmdOut = os.popen4("unzip -l -q "+archive)
		else:
			cmdIn, cmdOut = os.popen4("tar tvzf "+archive)

		for line in cmdOut.readlines():
			r=re.compile('[ \t\n]*'              # Skip leading whitespace
				'[ ]'
                	   )
			# Just do this simple for now
			bits = re.split(r, line)
			# This join was nice, but left blank spaces sometimes!
			#nubs = "".join(["<td>%s</td>" % (x) for x in bits])
			nubs = ""
			for x in bits:
				if (x != ""):
					nubs = nubs+"<td>"+x+"</td>"
			fileList.append(nubs)
	return fileList
