from parallels.plesk.source.plesk import messages
import logging
import posixpath

from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.utils import subscription_filter
from parallels.core.utils.paths import web_paths
from parallels.core.actions.content.web.copy_unix_content_base import TargetWebPathConverter
from parallels.core.utils import unix_utils

logger = logging.getLogger(__name__)


class FixUnixHtaccess(SubscriptionAction):
	"""Fix htaccess files for protected directories."""
	def get_description(self):
		return messages.ACTION_FIX_UNIX_HTACCESS_DESCRIPTION

	def get_failure_message(self, global_context, subscription):
		return messages.ACTION_FIX_UNIX_HTACCESS_FAILED.format(subscription_name=subscription.name)

	def is_critical(self):
		"""If action is critical or not

		If action is critical and it failed for a subscription, migration tool
		won't run the next operations for the subscription.

		:rtype: bool
		"""
		return False

	def filter_subscription(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		return subscription_filter.unix_with_virtual_hosting(
			subscription
		)

	def run(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""

		pdir = subscription.converted_dump.get_protected_dir()
		if pdir is None:
			return

		path = posixpath.join(
			TargetWebPathConverter().expand(
				web_paths.WebspaceDocumentRoot(subscription.converted_dump),
				subscription.web_target_server
			),
			pdir,
			'.htaccess'
		)
		with subscription.web_target_server.runner() as runner:
			if unix_utils.file_exists(runner, path):
				content = []
				for line in runner.get_file_contents(path).splitlines(True):
					if line.startswith('AuthType') or line.startswith('AuthName') or line.startswith('AuthUserFile'):
						continue
					content.append(line)
				runner.upload_file_content(path, ''.join(content))
