import posixpath

from parallels.common.actions.base.subscription_action import SubscriptionAction


class FixPermissions(SubscriptionAction):
	def get_description(self):
		return "Fix permissions for web files"

	def get_failure_message(self, global_context, subscription):
		return "Failed to fix permissions for web files of subscription '%s'" % (subscription.name)

	def filter_subscription(self, global_context, subscription):
		return True

	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 run(self, global_context, subscription):
		"""Set file owner and permissions for transferred subscription content.
		
		Plesk vhost permissions are described in 'Parallels Plesk Panel 12.0
		Advanced Administration Guide':
		http://download1.parallels.com/Plesk/PP12/12.0/Doc/en-US/online/plesk-linux-advanced-administration-guide/68806.htm
		"""
		target_vhost_dir = posixpath.join(
			subscription.web_target_server.vhosts_dir, 
			subscription.name.encode('idna')
		)
		sysuser_name = subscription.converted_backup.get_phosting_sysuser_name()
		find_options = {
			'find_path': target_vhost_dir,
			'owner': sysuser_name,
			'group': 'psacln',
		}
		chmod_commands = [
			dict(find_type='f', find_perm='o+r'),
			dict(find_type='d', find_perm='o+rx'),
		]

		with subscription.web_target_server.runner() as runner_target:
			for find_chmod_options in chmod_commands:
				runner_target.sh(
					u"/usr/bin/find {find_path} \
						-type {find_type} \
						-user {owner} -not -group root -not -group psaserv \
						-exec chown :{group} {{}} \; \
						-exec chmod {find_perm} {{}} \;",
					dict(find_options, **find_chmod_options)
				)

			vhost_log_dir = posixpath.join(
				subscription.web_target_server.vhosts_dir, 
				'system', subscription.name.encode('idna'), 'logs'
			)
			runner_target.sh(u"chown psaadm:psacln %s" % vhost_log_dir)
			runner_target.sh(
				u"chown :psaserv %s" % posixpath.join(target_vhost_dir, 'httpdocs')
			)
