#!/usr/bin/env php
<?php
/*

  check_nems_osb - Version 1.3
  Written by Robbie Ferguson for NEMS Linux
  -----
  1.3 - September 30, 2026 - RFC output on NEMS Linux 1.8 (Trixie) changed and broke the strtotime() due to not
                             conforming to PHP standard date formats. This has been fixed with $datestamp
  1.2 - July 12, 2023 - Report if the cloudauth command returns an offline response (NCS did not respond).
                        Improved state reporting (fixed some issues with the Migrator log to improve this).
  1.1 - May 21, 2021 - Remove the state output. Let NEMS use exit codes.
  1.0 - December 8, 2020 - Initial release

*/
  $auth=shell_exec('/usr/local/bin/nems-info cloudauth');
  if ($auth == 3) {
    // Offline State
    echo 'NEMS Cloud Services not responding (Internet down?).';
    exit(2);
  } else if ($auth == 0) {
    // UNKNOWN State
    echo 'NEMS Cloud Services not authorized.';
    exit(3);
  }

  $osb_log = '/var/log/nems/nems-osb.log';
  if (file_exists($osb_log)) {
    $line = trim(shell_exec('tail -n 1 ' . $osb_log));

    // Handle empty log file
    if (empty($line)) {
      echo 'NEMS Migrator OSB hasn\'t run yet.';
      exit(3);
    }

    $log = explode('::', $line);

    // Validate and parse date format safely
    $date = !empty($log[0]) ? DateTime::createFromFormat('D d M H:i:s T Y', $log[0]) : false;

    if ($date === false) {
      echo 'NEMS Migrator OSB state is unavailable.';
      exit(3);
    }

    $datestamp = $date->getTimestamp();

    if (isset($log[1])) {
      if ($log[1] == 2) {
        // CRITICAL State
        echo 'OSB ' . ($log[2] ?? '') . ': ' . trim($log[3] ?? '') . ' (' . date('l M j, Y g:i A',$datestamp) . ')';
        exit(2);
      } else if ($log[1] == 1 && $datestamp < strtotime('-2 days')) {
        // WARNING State
        echo 'Last OSB was ' . date('l M j, Y',$datestamp);
        exit(1);
      } else if ($log[1] == 1) {
        // OK State
        echo 'OSB ' . ($log[2] ?? '') . ' (' . date('l M j, Y',$datestamp) . ')';
        exit(0);
      } else if ($log[1] == '3') {
        // UNKNOWN State
        echo 'Unknown Error (' . date('l M j, Y',$datestamp) . ')';
        exit(3);
      }
    }
  } else {
    echo 'NEMS OSB has not yet run.';
    exit(3);
  }

  echo 'NEMS Migrator OSB state is unavailable.'; 
  exit(3);

?>
