import logging
from parallels.common.actions.base.common_action import CommonAction
from parallels.common.utils.migrator_utils import trace_step

logger = logging.getLogger(__name__)


class FetchBackupAction(CommonAction):
	def get_description(self):
		return u'Fetch data from source PPA Web SN'

	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		return u'Failed to fetch data from source PPA Web SN'

	def run(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		source_server = global_context.conn.get_source_node('Source')
		logger.debug(u"PPA host id where subscriptions web service is located: %s", 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 --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', 'running downloading backup', False, 'debug'):
				local_backup_filename = global_context.session_files.get_path_to_raw_plesk_backup('Source')
				source_runner.get_file(remote_backup_filename, local_backup_filename)

			with trace_step('fetch-source', 'running remove backup from source', False, 'debug'):
				source_runner.remove_file(remote_backup_filename)
