#!/usr/bin/php
<?php
/**
 * CLI entry point for scheduled and background Active Directory sync.
 * Scheduled via systemd timer; manual/resync via ombu-helper run_sync {run_id}.
 */

namespace {

ini_set('html_errors', false);
require_once('/usr/share/ombutel/www/includes/cli.php');

}

namespace ad_sync_cli {

use ombutel\ad_sync_config;
use modules\active_directory_sync\active_directory_syncRuns;
use modules\active_directory_sync\active_directory_syncSync;

$run_id = null;
foreach (isset($GLOBALS['argv']) ? $GLOBALS['argv'] : [] as $arg) {
	if (preg_match('/^--run-id=(\d+)$/', (string) $arg, $m)) {
		$run_id = (int) $m[1];
	}
}

if ($run_id) {
	active_directory_syncRuns::execute_run($run_id);
	$run = active_directory_syncRuns::load_run($run_id);
	if ($run && $run->status === 'success') {
		echo $run->message, "\n";
		exit(0);
	}
	if ($run && $run->message) {
		fwrite(STDERR, $run->message . "\n");
	}
	exit(1);
}

$config = ad_sync_config::load_config();
if (!$config) {
	fwrite(STDERR, "AD sync: no configuration row found.\n");
	exit(1);
}

if ((isset($config->sync_enabled) ? $config->sync_enabled : 'no') !== 'yes') {
	exit(0);
}

if (active_directory_syncRuns::tables_available()) {
	if (active_directory_syncRuns::has_running()) {
		fwrite(STDERR, "AD sync: another run is already in progress.\n");
		exit(0);
	}
	$run_id = active_directory_syncRuns::create_run(active_directory_syncRuns::TRIGGER_SCHEDULED);
	if ($run_id) {
		active_directory_syncRuns::execute_run($run_id);
		$run = active_directory_syncRuns::load_run($run_id);
		if ($run && $run->status === 'success') {
			echo $run->message, "\n";
			exit(0);
		}
		if ($run && $run->message) {
			fwrite(STDERR, $run->message . "\n");
		}
		exit(1);
	}
}

$result = active_directory_syncSync::run($config);
if ($result['ok']) {
	echo $result['message'], "\n";
	exit(0);
}

fwrite(STDERR, $result['message'] . "\n");
exit(1);

}
