from parallels.common.actions.base.subscription_action import SubscriptionAction
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 "Fix permissions for domains from IIS 6 with disabled ASP.NET"

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		return "Failed to fix permissions of files for subscription '%s'" % 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):
			plesk_utils.change_dedicated_iis_app_pool_state(
				global_context.conn.target.plesk_server,
				subscription.name,
				app_pool_state
			)