import logging
import os

import parallels.common.migrator

from parallels.common import MigrationError
from parallels.common.plesk_backup import save_backup_tar
from parallels.helm3_migrator.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(u"Can't get info from Helm, error is '%s'; migration was stopped." % e)		

	def save_backup(self, backup_save_file):
		if os.path.exists(backup_save_file):
			self.logger.debug(u"Remove previous 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.helm3_migrator.__path__]
		assert all(d == dirs[0] for d in dirs)
		return dirs[0]
