import logging

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

logger = logging.getLogger(__name__)

class ResetPermissions(SubscriptionAction):
	"""Reset file permissions on Windows like Plesk restore does"""
	
	def get_description(self):
		return "Fix file permissions for Windows"

	def get_failure_message(self, global_context, subscription):
		return "Failed to restore file permissions for subscription '%s'" % (subscription.name)

	def filter_subscription(self, global_context, subscription):
		return subscription_filter.windows_with_virtual_hosting(
			subscription
		)

	def run(self, global_context, subscription):
		vhost_name = subscription.name_idn
		sysuser_name = subscription.converted_backup.get_phosting_sysuser_name()
		if sysuser_name is not None:
			if ilen(subscription.raw_backup.iter_sites()) > 1: # there are subdomains or/and addon domains
				logger.debug(u"Update webspace subdomains security for the '%s' subscription",  vhost_name)
				global_context.import_api.update_webspace_subdomains_security_metadata_location(vhost_name)

		logger.debug(u"Repair permissions for the '%s' subscription", vhost_name)
		global_context.import_api.repair_webspace_security(vhost_name)
