import posixpath

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

logger = get_logger(__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
        """
        source_web_server = subscription.web_source_server
        if isinstance(source_web_server, PleskSourceServer):
            if source_web_server.plesk_version < (11, 5):
                logger.debug(messages.LOG_FIX_LOGS_DIRECTORIES_PERMISSION)
                with subscription.web_target_server.runner() as runner_target:
                    assert isinstance(runner_target, BaseRunner)
                    vhost_system_dir = subscription.web_target_server.get_vhost_system_dir(subscription.name)
                    logs_dir = posixpath.join(vhost_system_dir, 'logs')
                    runner_target.execute_command("/bin/chown psaadm:root {logs_dir}", dict(logs_dir=logs_dir))
                    runner_target.execute_command("/bin/chmod u=rwx,g=,o= {logs_dir}", dict(logs_dir=logs_dir))
