import logging

from parallels.core.actions.content.web.copy_unix_content_base import TargetWebPathConverter
from parallels.core.utils.paths import web_paths
from parallels.plesk.source.custom.web_files import CustomPanelWebFiles
from parallels.plesk.source.plesk.actions.content.web.copy_unix_content import CopyUnixWebContentBase


logger = logging.getLogger(__name__)


class CustomPanelCopyUnixWebContent(CopyUnixWebContentBase):
	"""Copy web content from custom panel's Unix server (access to the server was provided in configuration file)"""

	def filter_subscription(self, global_context, subscription):
		"""Check if we should run this action on given subscription or not

		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.plesk.source.custom.migrated_subscription.CustomPanelMigratedSubscription
		"""
		return (
			super(CustomPanelCopyUnixWebContent, self).filter_subscription(global_context, subscription)
			and
			global_context.conn.has_hosting_description_config(subscription.model.source)
		)

	def _list_files_to_copy(self, global_context, subscription):
		"""Make a list of source server directories and files to be transferred.

		Return:
			A list of (source directory -> destination directory) mappings

		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.plesk.source.custom.migrated_subscription.CustomPanelMigratedSubscription
		:rtype: list[parallels.core.utils.paths.copy_web_content.CopyWebContentItem]
		"""
		return CustomPanelWebFiles().list_files_to_copy(global_context, subscription)

	def run(self, global_context, subscription):
		"""Run action on given subscription

		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.plesk.source.custom.migrated_subscription.CustomPanelMigratedSubscription
		"""
		super(CustomPanelCopyUnixWebContent, self).run(global_context, subscription)
		self._fix_document_root_permissions(subscription)

	def _fix_document_root_permissions(self, subscription):
		"""Fix permissions on document root directories for subscription, subdomains and addon domains

		:type subscription: parallels.plesk.source.custom.migrated_subscription.CustomPanelMigratedSubscription
		"""
		server = subscription.web_target_server
		system_user = subscription.converted_dump.phosting_sysuser_name
		with server.runner() as runner:
			target_path = TargetWebPathConverter().expand(
				web_paths.WebspaceDocumentRoot(subscription.converted_dump), server
			)
			self._fix_path_document_root_permissions(runner, system_user, target_path)
			for site in subscription.converted_dump.iter_sites():
				target_path = TargetWebPathConverter().expand(
					web_paths.SiteDocumentRoot(subscription.converted_dump, site), server
				)
				self._fix_path_document_root_permissions(runner, system_user, target_path)

	@staticmethod
	def _fix_path_document_root_permissions(runner, system_user, target_path):
		"""Fix permissions on document root located in specified path

		:type system_user: str | unicode
		:type target_path: str | unicode
		"""
		runner.sh('chown -R {user}:{group} {path}', args=dict(
			user=system_user,
			group='psacln',
			path=target_path
		))
		runner.sh('chgrp {group} {path}', args=dict(
			group='psaserv',
			path=target_path
		))