import logging

from parallels.common import MigrationError
from parallels.common.content.mail.rsync import CopyMailRsync
from parallels.common.content.mail.rsync import TargetMailDomainDirectory
from parallels.common.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(), TargetMailDomainDirectory())]
		elif stdout.strip() == u"domain %s does not exist" % self.domain.name.encode('idna'):
			logger.info(
				u"Skipped copying mail content of domain %s because such mail domain does not exist on source server", 
				self.domain.name
			)
		else:
			raise MigrationError(
				u"Unable to determine the path to the mail domain %s on the source server at %s: %s\n%s\n"
				u"The migration tool will not copy to PPA the mail content of this domain.\nCopy it manually." % (
					self.domain.name, self.subscription.mail_source_server.ip(), 
					stdout, stderr
				)
			)
