from parallels.common.utils.restore_hosting_utils import restore_hosting_settings_lock
from parallels.plesks_migrator import messages
from parallels.common.actions.base.subscription_action import SubscriptionAction
from parallels.common.target_panels import TargetPanels
from parallels.common.utils import subscription_filter
from parallels.common.utils import plesk_utils


class FixPermissionsForIIS6Domains(SubscriptionAction):
	"""Fix permissions for domains from IIS 6 with ASP.NET disabled

	Workaround for IIS 6 domains with ASP.NET disabled, but dedicated
	application pool enabled: IWPD* user had no access to httpdocs
	directory on source node in such situation, but in IIS 7 IWPD* user
	must have access to read web.config, otherwise the whole site won't
	work. The most easy way to fix that - disable and then enable
	dedicated application pool which will fix permissions both on
	filesystem and in '.Security' file
	"""

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

	def get_description(self):
		return messages.ACTION_FIX_PERMISSIONS_FOR_IIS6_DOMAIN_DESCRIPTION

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		return messages.ACTION_FIX_PERMISSIONS_FOR_IIS6_DOMAIN_FAILURE % 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 run(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		for app_pool_state in (False, True):
			with restore_hosting_settings_lock:
				plesk_utils.change_dedicated_iis_app_pool_state(
					global_context.conn.target.plesk_server,
					subscription.name,
					app_pool_state,
					plesk_restore_mode=global_context.target_panel != TargetPanels.PPA
				)
