from parallels.source.hsphere import messages
import logging

from parallels.core import MigrationError
from parallels.core.content.mail.rsync import CopyMailRsync
from parallels.core.utils.paths.mail_paths import MailDomainDirectory
from parallels.core.content.mail.rsync import SourceMailDirectory

logger = logging.getLogger(__name__)


class HSphereCopyMailContent(CopyMailRsync):
	"""Transfer mail content from H-Sphere to PPA Unix server
	
	Mail paths/files are the same for Plesk and H-Sphere server
	"""

	def __init__(self):
		super(HSphereCopyMailContent, self).__init__(HSphereSourceMailDirectory)


class HSphereSourceMailDirectory(SourceMailDirectory):
	def prepare(self):
		with self.subscription.mail_source_server.runner() as runner:
			errcode, stdout, stderr = runner.sh_unchecked(
				'/hsphere/local/var/vpopmail/bin/vdominfo -d {domain}',
				dict(domain=self.domain.name.encode('idna'))
			)

		if errcode == 0:
			return [(stdout.strip(), MailDomainDirectory())]
		elif stdout.strip() == u"domain %s does not exist" % self.domain.name.encode('idna'):
			logger.info(
				messages.SKIPPED_COPYING_MAIL_CONTENT_DOMAIN_DOES_NOT_EXIST_ON_SOURCE,
				self.domain.name
			)
		else:
			raise MigrationError(
				messages.UNABLE_DETERMINE_PATH_TO_MAIL_DOMAIN_ON_SOURCE % (
					self.domain.name, self.subscription.mail_source_server.ip(), 
					stdout, stderr
				)
			)
