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 FixUnixPermissionsOldPlesks(SubscriptionAction):
	"""
	On Plesk 8/9 statistics and logs directories are owned by root, while in
	Plesk >= 10.x they are owned by domain's sysuser.  We need to update
	permissions as otherwise we will get "filemng: stat failed: Permission
	denied" error while trying to view logs from Plesk CP.
	"""

	def get_description(self):
		return "Set permissions for statistics and logs directories"

	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 set permissions for statistics and logs directories 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 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()
		vhost_dir = posixpath.join(
			subscription.web_target_server.vhosts_dir,
			subscription.name.encode('idna')
		)

		if subscription.web_source_server.plesk_major_version in (8, 9):
			if sysuser_name is not None:
				logger.debug(u"Fix statistics and logs directories permission after migration from Plesk 8/9")
				statistics_dir = posixpath.join(vhost_dir, 'statistics')
				logs_dir = posixpath.join(statistics_dir, 'logs')
				with subscription.web_target_server.runner() as runner_target:
					runner_target.run("/bin/chown", [sysuser_name, statistics_dir])
					runner_target.run("/bin/chown", [sysuser_name, logs_dir])
					runner_target.run("/bin/chmod", ['u=rx,g=rx,o=', logs_dir])
