#!/usr/bin/php -q
<?php

define("SUBSYSTEM", 1);

require_once(dirname(__FILE__) . '/../html/includes/constants.inc.php');
require_once(dirname(__FILE__) . '/../html/config.inc.php');
require_once(dirname(__FILE__) . '/../html/includes/utils.inc.php');
require_once(dirname(__FILE__) . '/../html/includes/components/oauth2/sso-ajaxhelper-functions/sso-migration.php');

if (!db_connect_all()) {
    fwrite(STDERR, "Unable to connect to Nagios XI databases.\n");
    exit(1);
}

try {
    $result = migrate_sso_user_meta_to_database();
    if (!empty($result['already_migrated'])) {
        echo "SSO user metadata already migrated.\n";
    } else {
        echo "Migrated {$result['migrated']} SSO user mapping(s) from legacy user meta.\n";
    }
    exit(0);
} catch (Exception $e) {
    fwrite(STDERR, "SSO user metadata migration failed: " . $e->getMessage() . "\n");
    exit(1);
}

