import logging
import posixpath

from parallels.common.actions.base.subscription_action import SubscriptionAction
from parallels.common.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 "Fix permissions for vhost directory"

	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 for vhost directory of 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 filter_subscription(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		return subscription_filter.unix_with_virtual_hosting(
			subscription
		)

	def run(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		sysuser_name = subscription.converted_backup.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
			])
