import posixpath

from parallels.core.runners.base import BaseRunner


class CopyMailLocalDir(object):
    """Copy mail messages from directory already located on the target server, for target Unix server"""

    @staticmethod
    def copy_mailbox(subscription, mailbox, source_directory):
        """
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :type mailbox: parallels.core.dump.data_model.Mailbox
        :type source_directory: str | unicode | None
        :rtype: None
        """
        server = subscription.mail_target_server
        with server.runner() as runner:
            assert isinstance(runner, BaseRunner)
            target_path = posixpath.join(
                subscription.mail_target_server.mail_dir,
                mailbox.domain_name.encode('idna').lower(),
                mailbox.name.lower()
            )
            runner.execute_command("/usr/bin/rsync --archive --timeout=30 {source} {target}", dict(
                source=source_directory + '/', target=target_path
            ))
            runner.execute_command(u'chown popuser:popuser -R {path}', dict(path=target_path))
