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):
		return "Failed to fix permissions for vhost directory of subscription '%s'" % (subscription.name)

	def filter_subscription(self, global_context, subscription):
		return subscription_filter.unix_with_virtual_hosting(
			subscription
		)

	def run(self, global_context, subscription):
		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
			])
