from parallels.shm_web_sn.source.shm_web_sn import messages
import logging
from parallels.core.actions.base.common_action import CommonAction
from parallels.core.utils.migrator_utils import trace_step

logger = logging.getLogger(__name__)


class FetchBackupAction(CommonAction):
	def get_description(self):
		return messages.FETCH_DATA_FROM_SOURCE_PPA_WEB_SN

	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		return messages.FAILED_TO_FETCH_DATA_FROM_SOURCE_PPA_WEB_SN

	def run(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		source_server = global_context.conn.get_source_node('Source')
		logger.debug(messages.PPA_HOST_ID_OF_WEB_SERVICE, source_server.ppa_host_id)
		remote_backup_filename = source_server.get_session_file_path(
			u'pleskbackup.%s' % (u'zip' if source_server.is_windows() else u'tar')
		)
		with source_server.runner() as source_runner:
			with trace_step('fetch-source', 'running pleskbackup', False, 'debug'):
				source_runner.sh(
					u'{pleskbackup} --domains-name {webspace_name} --configuration '
					u'--only-hosting --verbose --output-file={output_file}',
					dict(
						pleskbackup=source_server.get_bin_util_path(u'pleskbackup'),
						output_file=remote_backup_filename, webspace_name=global_context.webspace_name
					),
					env=dict(PRODUCT_MODE=u'SHM', PLESK_DIR=source_server.plesk_dir))

			with trace_step('fetch-source', messages.RUNNING_DOWNLOADING_BACKUP, False, 'debug'):
				local_backup_filename = global_context.session_files.get_raw_dump_filename('Source')
				source_runner.get_file(remote_backup_filename, local_backup_filename)

			with trace_step('fetch-source', messages.RUNNING_REMOVE_BACKUP_FROM_SOURCE, False, 'debug'):
				source_runner.remove_file(remote_backup_filename)
