from parallels.common.actions.base.subscription_action import SubscriptionAction
from parallels.common.utils import subscription_filter
from parallels.common.utils import plesk_utils


class FixPermissionsForClientsIISPools(SubscriptionAction):
	"""Fix permissions for domains which had client's/reseller's pool

	Workaround for domains that had shared client's or reseller's
	application pool before migration. They may be moved to some other
	application pool (by default - common Plesk shared pool).  That pool
	may have another system username, and '.Security' file will become
	invalid. To fix '.Security' file and corresponding permissions on
	filesystem, we enable and then disable dedicated application pool.
	"""
	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_disabled(
				subscription
			)
			and 
			# Applicable only for PPA 11.5/11.6, consider to be removed in
			# further versions
			subscription.web_target_server.plesk_version < (12, 0)
		)

	def get_description(self):
		return "Fix permissions for domains with client's or reseller's application pool"

	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 (True, False):
			plesk_utils.change_dedicated_iis_app_pool_state(
				global_context.conn.target.plesk_server,
				subscription.name,
				app_pool_state
			)