<?php
  header('Content-Type: application/json');
  function decypher(string $name): ?string {
    $openssl = 'C:\Program Files\FireDaemon OpenSSL 3\bin\openssl.exe';
    $cmsFile = "F:\\Include\\dat\\$name.p7m";
    $certPem = "F:\\Include\\certs\\cert_only.pem";
    $keyPem  = "F:\\Include\\certs\\key_only.pem";

    foreach ([$openssl,$cmsFile,$certPem,$keyPem] as $p) {
      if (!is_file($p)) { error_log("Missing file: $p"); return null; }
    }

    $cmd = '"' . $openssl . '" cms -decrypt -inform PEM'
      . ' -in '    . escapeshellarg($cmsFile)
      . ' -recip ' . escapeshellarg($certPem)
      . ' -inkey ' . escapeshellarg($keyPem)
      . ' -out -';

    $spec = [
      0 => ['pipe','r'],   // stdin (unused)
      1 => ['pipe','w'],   // stdout -> texte déchiffré
      2 => ['pipe','w'],   // stderr -> erreurs OpenSSL
    ];
    $proc = proc_open($cmd, $spec, $pipes);
    if (!is_resource($proc)) { error_log('proc_open failed'); return null; }
    fclose($pipes[0]); // rien à envoyer en stdin

    $stdout = stream_get_contents($pipes[1]); fclose($pipes[1]);
    $stderr = stream_get_contents($pipes[2]); fclose($pipes[2]);
    $code = proc_close($proc);

    if ($code !== 0) {
      error_log("OpenSSL failed (code $code): $stderr");
      return null;
    }
    return $stdout;
  }
  function DB_INFRA() {
    $user="INFRA_dbo";
    $pwd=decypher("infra");
    $server="DUN-PRD-R1MSSQL.armony.net\PRD";
    $database="INFRA";
    $conn = odbc_connect("Driver={SQL Server};Server=$server;Database=$database;", $user, $pwd);
    return $conn ;
  }
  if (isset($_GET['term'])) {
    $term = $_GET['term'];
    $query = "SELECT hostname AS serv FROM cmdb_srvall WHERE hostname LIKE '%$term%' UNION SELECT hostname AS serv FROM x_SRVALL WHERE hostname LIKE '%$term%'";
    $conn = DB_INFRA();
    $rs = odbc_exec($conn, $query);
    while ($row = odbc_fetch_array($rs)) {
      $servers[] = $row;
    }
    $result = [];
    if (is_array($servers)) {
        foreach ($servers as $server) {
            $result[] = $server['serv'];
        }
    }
    echo json_encode($result);
  }
