import logging
import posixpath

from parallels.plesk.source.custom import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction


logger = logging.getLogger(__name__)


class CustomPanelCopyUnixMailContentLocal(SubscriptionAction):
	"""Put Unix mail messages files that are already on target server to correct locations

	This action is applicable when access to the server was not provided in configuration file, and customer
	has already copied mail message files from the source server to the target server
	"""

	def get_description(self):
		"""Get short description of action as string

		:rtype: str
		"""
		return messages.ACTION_COPY_LOCAL_MAIL_FILES

	def get_failure_message(self, global_context, subscription):
		"""Get message for situation when action failed

		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		return messages.FAIL_TO_COPY_LOCAL_MAIL_FILES

	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 (
			subscription.hosting_description is not None
			and
			# source mail server is not specified, we don't have access to it, so
			# if customer has specified some files to copy, we consider that they all are already
			# on the target server
			subscription.mail_source_server is None
			and
			subscription.mail_target_server is not None
			and
			not subscription.is_windows
		)

	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
		"""
		server = subscription.mail_target_server
		for mailbox in subscription.hosting_description.iter_mailboxes():
			with server.runner() as runner:
				source_path = mailbox.source_directory
				if source_path is None:
					continue

				target_path = posixpath.join(
					subscription.mail_target_server.mail_dir, mailbox.domain_name, mailbox.short_name.encode('idna')
				)
				runner.run(u"/usr/bin/rsync", [u"--archive", source_path + '/', target_path])
				runner.sh(u'chown popuser:popuser -R {path}', dict(path=target_path))
