<?php

/**
 * Petit script permettant d'avoir les infos de facturation
 * sur les services dont le renouvellement est proche.
 *
 * Le fichier .auth-api-ovh.ini permet de stocker les identifiants de connexion
 * et ressemble à :
 *  login = xxNNNNN-ovh
 *  password = xxxxxxxxxxxxxxx
 */
define('STATE_OK',        0);
define('STATE_WARNING',   1);
define('STATE_CRITICAL',  2);
define('STATE_UNKNOWN',   3);
define('STATE_DEPENDENT', 4);


// Reading commande line options
$options = getopt('w:c:h');
if (in_array('h', $options)) {
	echo <<<EOT
  -w warning_level
  -c critical_level
EOT;
	exit(0);
}

$compil = array(
	STATE_WARNING  => array('arg' => 'w', 'intitule' => 'warning'),
	STATE_CRITICAL => array('arg' => 'c', 'intitule' => 'critical'),
	);
$finalMsg = array(
	STATE_OK => 'OK',
	STATE_WARNING => 'WARNING:',
	STATE_CRITICAL => 'CRITICAL:',
	);
$finalState = STATE_OK;

// Checking values in command line arguments
foreach ($compil as $item) {
	if ( ! isset($options[$item['arg']])) {
		printf("ERROR: Missing argument '%s' (%s).\n", $item['arg'], $item['intitule']);
		exit(STATE_UNKNOWN);
	}
	$options[$item['arg']] = (int) $options[$item['arg']];
	if ($options[$item['arg']] <= 0) {
		printf("ERROR: Unacceptable value for '%s' (%s).\n", $item['arg'], $item['intitule']);
		exit(STATE_UNKNOWN);
	}
}
if ($options['c'] > $options['w']) {
	echo "ERROR: warning level lower than critical level.\n";
	exit(STATE_UNKNOWN);
}

// Lecture des informations de connexion
if ( ! ($identifiants = parse_ini_file('.auth-api-ovh.ini'))) {
    echo "ERREUR: Impossible de récupérer les identifiants de connexion à l'API OVH.\n";
    exit(STATE_UNKNOWN);
}

try {
	$soap = new SoapClient("https://www.ovh.com/soapi/soapi-re-1.59.wsdl");

	//login
	$session = $soap->login($identifiants['login'], $identifiants['password'],"fr", false);

	// checks...
	$listingExpirations = $soap->billingGetReferencesToExpired($session, $options['w']);
	// We try to avoid making a second call to the OVH API
	// (no wasting of resources :)
	// so we check, for each element, if the expiration delay is below the
	// critical level
	foreach ($listingExpirations as $item) {
		if (strtotime($item->expired) < (time() + 86400 * $options['c'])) {
			$finalMsg[STATE_CRITICAL] .= ' [' . $item->name . '(' . $item->type . ') will expire at ' . $item->expired . ']';
			$finalState = STATE_CRITICAL;
		} else {
			$finalMsg[STATE_WARNING] .= ' [' . $item->name . '(' . $item->type . ') will expire at ' . $item->expired . ']';
			if ($finalState == STATE_OK)
				$finalState = STATE_WARNING;
		}
	}

	//logout
	$soap->logout($session);
} catch(SoapFault $fault) {
	echo "ERREUR: soapi: " . $fault;
	exit(STATE_UNKNOWN);
}

// Code de retour Ok
echo $finalMsg[$finalState] . "\n";
exit($finalState);