from parallels.source.plesk 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 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 messages.ACTION_FIX_UNIX_PERMISSIONS_ON_OLD_PLESKS_DESCRIPTION

	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.ACTION_FIX_UNIX_PERMISSIONS_ON_OLD_PLESKS_FAILURE % 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_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(messages.LOG_FIX_STATISTICS_AND_LOGS_DIRECTORIES_PERMISSION)
				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])
