#!/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>, May 2017
	 */

	use Opcenter\Account\Delete;
	use Opcenter\Account\DomainOperation;
	use Opcenter\Account\Enumerate;
	use Opcenter\Account\State;
	use Opcenter\Lock;

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

	$args = [];
	DomainOperation::preExecutionHook($args);

	$args = Opcenter\CliParser::parse();
	Lock::lock();

	$status = Delete::RC_SUCCESS;
	$siteBuffers = [];

	$sites = array_reverse(array_cardinal(array_map(static function ($spec) {
		$site = 'site' . \Auth::get_site_id_from_anything($spec);
		if ($site === 'site') {
			error("unknown site/domain/identifier `%s'", $spec);
			return null;
		}
		return $site;
	}, $sites = \Opcenter\CliParser::getSiteFromArgs(...array_get($args, 'command')))));

	if (!empty($args['options']['since'])) {
		if (!$sites) {
			$sites = Enumerate::disabled();
		}
		$time = $args['options']['since'];
		$sites = array_filter($sites, static function ($site) use ($time) {
			$marker = Opcenter\Account\State::disableMarker($site);
			if (!file_exists($marker)) {
				warn("No disable marker found for `%s'. Site metadata directory missing? Ignoring removal request.", $site);
				return false;
			}
			$ctime = filectime($marker);
			return $ctime <= $time;
		});
	}

	if (empty($sites) && !isset($args['options']['since'])) {
		exit(1^error("No sites specified"));
	}

	$matcher = strtr($args['options']['match'] ?? '', ['#' => '\\#']);

	foreach ($sites as $site) {
		$force = $args['options']['force'] ?? false;
		if ($matcher) {
			$reason = file_get_contents(State::disableMarker($site));
			if (!preg_match("#{$matcher}#", $reason)) {
				continue;
			}
		}

		if (!empty($args['options']['dry'])) {
			$ts = filemtime(State::disableMarker($site)) ?: null;
			$timespec = $ts ? 'suspension date %s' :  'no suspension date';
			info('%s (%s; %s) will be deleted',
				$site,
				\Auth::get_domain_from_site_id(substr($site, 4)),
				sprintf($timespec, $ts ? date('Y-m-d', $ts) : null)
			);
			continue;
		}

		$oldex = \Error_Reporter::exception_upgrade(\Error_Reporter::E_FATAL);
		$instance = null;
		try {
			$instance = new Delete($site, ['force' => $force]);
			$domain = $instance->getDomain();
			$oldex = \Error_Reporter::exception_upgrade(\Error_Reporter::E_FATAL);
			try {
				\cli\cmd(null, $site);
			} catch (\apnscpException) {

			} finally {
				\Error_Reporter::exception_upgrade($oldex);
			}
			$ret = $instance->exec();
		} catch (\Throwable $e) {
			error("failed to remove site `%s': %s", $site, $e->getMessage(), $e);
		} finally {
			\Error_Reporter::exception_upgrade($oldex);
			$siteBuffers[$site] = \Error_Reporter::flush_buffer();
		}

		$buffer = Error_Reporter::get_buffer();
		$status = max($status, $instance ? $instance->getStatus() : \Error_Reporter::E_ERROR);
		dlog('Deleted %s, %s (%x) %s',
			$site,
			$domain ?? 'NULL',
			strtoupper(Error_Reporter::error_type(Error_Reporter::get_severity()) ?: 'success'),
			($instance ? $instance->getStatus() : DomainOperation::RC_FAILURE) === DomainOperation::RC_FAILURE ?
				'Failed' : 'Succeeded'
		);
	}

	// restore buffer for result log
	array_map(static function ($buf) {
		\Error_Reporter::set_buffer($buf);
	}, $siteBuffers);

	exit ($status);