from parallels.source.helm3 import messages
import logging
import os

import parallels.core.migrator

from parallels.core import MigrationError
from parallels.core.plesk_backup import save_backup_tar
from parallels.source.helm3.helm3_agent import Helm3Agent

class BackupAgent:
	logger = logging.getLogger(__name__)

	def __init__(self, server):
		self.server = server 

	def make_backup(self, args=[]):
		try:
			helm_agent = Helm3Agent(self.server)
			helm_agent.run(args)
		except Exception as e:
			self.logger.debug(u'Exception:', exc_info=e)
			raise MigrationError(messages.CANNOT_GET_INFO_FROM_HELM % e)

	def save_backup(self, backup_save_file):
		if os.path.exists(backup_save_file):
			self.logger.debug(messages.LOG_REMOVE_EXISTING_BACKUP_FILE)
			os.remove(backup_save_file)

		backup_xml_file_name = os.path.dirname(backup_save_file) + '/backup.xml'
		with self.server.runner() as runner:
			runner.get_file(
				self.server.get_session_file_path("backup.xml"), 
				backup_xml_file_name
			)

		with open(backup_xml_file_name) as backup_file:
			save_backup_tar(backup_file.read(), backup_save_file)

	def _get_helm3_extras_local_path(self, filename):
		return os.path.join(self._get_helm3_migrator_root_path(), 'extras', filename)

	def _get_helm3_migrator_root_path(self):
		# Get path to package root directory.
		dirs = [p for p in parallels.source.helm3.__path__]
		assert all(d == dirs[0] for d in dirs)
		return dirs[0]
