from contextlib import contextmanager
from parallels.core.utils import unix_utils
from parallels.core.utils.common import cached


class UnixServer(object):
	@property
	@cached
	def is_centos(self):
		with self.runner() as runner:
			return unix_utils.is_centos(runner)

	@property
	@cached
	def is_debian(self):
		with self.runner() as runner:
			return unix_utils.is_debian(runner)

	@property
	@cached
	def is_suse(self):
		with self.runner() as runner:
			return unix_utils.is_suse(runner)


	@property
	@cached
	def apache_httpd_conf(self):
		with self.runner() as runner:
			return unix_utils.get_apache_httpd_conf(runner)

	@property
	@cached
	def apache_user(self):
		with self.runner() as runner:
			# Try to find username in system. If can't do it, then take default name.
			apache_user = unix_utils.get_apache_user(runner, self.apache_httpd_conf)
			if apache_user is not None:
				return apache_user
			elif self.is_debian:
				return 'www-data'
			elif self.is_suse:
				return 'wwwrun'
			else:
				return 'apache'

	@property
	@cached
	def apache_group(self):
		with self.runner() as runner:
			# Try to find groupname in system. If can't do it, then take default name.
			apache_group = unix_utils.get_apache_group(runner, self.apache_httpd_conf)
			if apache_group is not None:
				return apache_group
			elif self.is_debian:
				return 'www-data'
			elif self.is_suse:
				return 'www'
			else:
				return 'apache'

	@contextmanager
	def runner(self):
		"""Get runner object to execute commands on the source server"""
		raise NotImplementedError()