#!/usr/bin/env php
<?php
if ($argc < 2) {
    fwrite(STDERR, "Usage: nice-monitoring-template-plan '<metadata>' [--all]\n");
    exit(2);
}
$metadata = $argv[1];
$showAll = in_array('--all', $argv, true);
$path = '/usr/share/nice-monitoring/catalog/template-map.json';
$j = json_decode(file_get_contents($path), true);
if (!is_array($j)) {
    fwrite(STDERR, "Invalid catalog\n");
    exit(3);
}
$out = [
    'metadata' => $metadata,
    'auto' => [],
    'deferred' => []
];
foreach ($j['rules'] as $rule) {
    $match = true;
    foreach ($rule['match_all'] as $needle) {
        if (strpos($metadata, $needle) === false) {
            $match = false;
            break;
        }
    }
    if (!$match) continue;

    $entry = [
        'rule' => $rule['id'],
        'mode' => $rule['mode'],
        'templates' => $rule['templates'],
        'reason' => $rule['reason']
    ];
    if ($rule['mode'] === 'auto') {
        $out['auto'][] = $entry;
    }
    elseif ($showAll) {
        $out['deferred'][] = $entry;
    }
}
echo json_encode($out, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), PHP_EOL;
