from parallels.core import messages
import logging
import posixpath

from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.utils import subscription_filter

logger = logging.getLogger(__name__)


class FixUnixVhostPermissions(SubscriptionAction):
	"""Fix file ownership for vhost domain directory after moving."""

	def get_description(self):
		return messages.FIX_PERMISSIONS_FOR_VHOST_DIRECTORY

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		return messages.FAILED_FIX_PERMISSIONS_FOR_VHOST_DIRECTORY % 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
		"""
		sysuser_name = subscription.converted_dump.get_phosting_sysuser_name()
		target_vhost_dir = posixpath.join(
			subscription.web_target_server.vhosts_dir, 
			subscription.name_idn
		)
		with subscription.web_target_server.runner() as runner_target:
			runner_target.run("/bin/chown", [
				"%s:psaserv" % sysuser_name,
				target_vhost_dir 
			])
			runner_target.run("/bin/chmod", [
				"u=rwx,g=x,o=", target_vhost_dir
			])
