import posixpath

from parallels.core.logging import get_logger
from parallels.core import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.runners.base import BaseRunner
from parallels.core.utils import subscription_filter

logger = get_logger(__name__)


class FixUnixVhostPermissions(SubscriptionAction):
    """Fix file ownership for vhost domain directory after moving."""

    def get_description(self):
        return messages.FIX_PERMISSIONS_FOR_VHOST_DIRECTORY

    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.FAILED_FIX_PERMISSIONS_FOR_VHOST_DIRECTORY % 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_dump.get_phosting_sysuser_name()
        vhost_name = subscription.name_idn
        if subscription.web_target_server.get_plesk_version()[:2] >= (17, 9):
            vhost_name = vhost_name.lower()
        target_vhost_dir = posixpath.join(
            subscription.web_target_server.vhosts_dir, 
            vhost_name
        )
        with subscription.web_target_server.runner() as runner_target:
            assert isinstance(runner_target, BaseRunner)
            runner_target.execute_command(
                "/bin/chown {sysuser_name}:psaserv {target_vhost_dir}",
                dict(sysuser_name=sysuser_name, target_vhost_dir=target_vhost_dir)
            )
            runner_target.execute_command(
                "/bin/chmod u=rwx,g=x,o= {target_vhost_dir}",
                dict(target_vhost_dir=target_vhost_dir)
            )
