import ntpath
import posixpath

class WindowsSessionDir(object):
	"""Session directory for migration files on Windows"""

	def __init__(self, runner_cm, session_dir):
		"""Create object
		
		Arguments:
		- runner_cm - contextmanager that could create runner object
		which is an instance of common.run_command.*Runner
		- session_dir - path to the session directory
		"""
		self._runner_cm = runner_cm
		self._session_dir = session_dir
		self._created = False

	def get_file_path(self, filename):
		"""Get full path to a file identified by filename
		
		Initializes session directory in a lazy way - when you first request
		file path, session directory is created.

		Arguments:
		- filename - string, relative name of a file
		"""
		if not self._created:
			self._create()
			self._created = True

		return ntpath.join(self._session_dir, filename)

	def get_session_dir_path(self):
		"""Get path of a session directory"""
		return self._session_dir

	def _create(self):
		"""Create session directory"""

		with self._runner_cm() as runner:
			runner.mkdir(self._session_dir)
			# check if setting inheritance is allowed by icacls built-in tool
			# by checking it's help
			if '/inheritance' in runner.sh('icacls /?'):
				icacl_commands = [
					'/inheritance:r', 
					'/grant Administrators:(OI)(CI)F',
					'/grant SYSTEM:(OI)(CI)F'
				]
				for icacl_command in icacl_commands:
					runner.sh(
						"icacls {session-dir} %s" % (icacl_command,),
						{'session-dir': self._session_dir}
					)
			else:
				# If there is no 'inheritance' option for icacls, there is no
				# simple way to set permissions allowing to temporary migration
				# files only by Administrator.  That is possible on Windows
				# 2003 Permissions will be inherited, and we consider that it
				# is a migration tool's user responsibility to set permissions
				# for a directory for temporary files
				pass

class UnixSessionDir(object):
	"""Session directory for migration files on Linux"""

	def __init__(self, runner_cm, session_dir):
		"""Create object
		
		Arguments:
		- runner_cm - contextmanager that could create runner object
		which is an instance of common.run_command.*Runner
		- session_dir - path to the session directory
		"""
		self._runner_cm = runner_cm
		self._session_dir = session_dir
		self._created = False

	def get_file_path(self, filename):
		"""Get full path to a file identified by filename
		
		Initializes session directory in a lazy way - when you first request
		file path, session directory is created.

		Arguments:
		- filename - string, relative name of a file
		"""
		if not self._created:
			self._create()
			self._created = True

		return posixpath.join(self._session_dir, filename)

	def get_session_dir_path(self):
		"""Get path of a session directory"""
		return self._session_dir

	def _create(self):
		"""Create session directory"""

		with self._runner_cm() as runner:
			runner.mkdir(self._session_dir)
			# TODO set permissions
