#!/usr/bin/env apnscp_php
<?php
	/**
	 * Copyright (C) Apis Networks, Inc - All Rights Reserved.
	 *
	 * Unauthorized copying of this file, via any medium, is
	 * strictly prohibited without consent. Any dissemination of
	 * material herein is prohibited.
	 *
	 * For licensing inquiries email <licensing@apisnetworks.com>
	 *
	 * Written by Matt Saladna <matt@apisnetworks.com>, June 2019
	 */

	use Opcenter\Account\Import;

	$time = time();

	define('INCLUDE_PATH', dirname(__DIR__));
	include INCLUDE_PATH . '/lib/CLI/cmd.php';

	$args = [];
	register_shutdown_function(static function () use (&$args) {
		if (is_debug() || array_get($args, 'options.output') === 'json') {
			// already listed or to be listed
			return;
		}
		$class = Error_Reporter::E_ERROR | Error_Reporter::E_FATAL |
			Error_Reporter::E_EXCEPTION | Error_Reporter::E_WARNING;
		foreach (Error_Reporter::get_buffer($class) as $e) {
			fwrite(STDERR, Error_Reporter::errno2str($e['severity']) . ': ' . $e['message'] . "\n");
		}
	});

	$args = \Opcenter\Migration\CliParser::parse('import');

	$file = array_get($args, 'command.0');
	if (!array_get($args, 'options.list-components') && !file_exists($file)) {
		fatal("Requested backup `%s' does not exist", $file);
	}

	$c = cli\cmd(null);
	if (!is_object($c)) {
		fatal('Failed to create CLI object');
	}
	$instance = new Import($file, array_get($args, 'options', []));

	if (null !== ($plan = array_get($args, 'options.plan'))) {
		$instance->setOption('plan', $plan);
	}
	$ret = false;
	try {
		$ret = $instance->exec();
	} catch (\Throwable $e) {
		Error_Reporter::handle_exception($e);
	}
	// "edit" hooks are embedded in Opcenter/Account/Edit
	$domain = $instance->getDomain();
	$buffer = Error_Reporter::get_buffer();
	$macro = !Error_Reporter::is_error() ? 'success' : 'error';
	$time = time() - $time;
	// ensure status always reported
	Error_Reporter::set_verbose();
	$macro('Imported %s, %s %s (severity: %s, duration: %\'02d:%\'02d:%\'02d)',
		$file,
		$domain,
		$ret && !Error_Reporter::is_error() ? 'Succeeded' : 'Failed',
		strtoupper(Error_Reporter::error_type(Error_Reporter::get_severity()) ?: 'success'),
		$time / 3600, $time / 60, $time % 60
	);
	//cli\dump_buffer($buffer);
	exit ($instance->getStatus());