#!/usr/bin/php
<?php
/**
 * Checks .pl (Polish) domains. Triggers warning when domain is about to expire.
 * Usage ./check_domain_pl.php -d domain.pl [-c <days_critical>] [-w <days_warning>]
 * 
 * @version 0.1
 * @author Piotr Polak <pepis@closbrothers.pl>
 * @link http://www.closbrothers.pl/
 * @license http://www.gnu.org/licenses/gpl.html GPL
 */

$arguments = getopt('d:w:c:');

$days_warning_treshold = 30;
$days_critical_treshold = 0;
if( isset($arguments['w']) && is_numeric( $arguments['w'] ) )
{
	$days_warning_treshold = $arguments['w'];
}
if( isset($arguments['c']) && is_numeric( $arguments['c'] ) )
{
	$days_critical_treshold = $arguments['c'];
}

if( !isset($arguments['d']) )
{
	fwrite(STDOUT, "ERROR: Usage ./check_domain_pl.php -d domain.pl [-c <days_critical>] [-w <days_warning>]\n");
	exit(3);
}

if( strpos($arguments['d'], '.pl') === FALSE )
{
	fwrite(STDOUT, "ERROR: Domain must be *.pl\n");
	exit(3);
}

$output = array();
$code = @exec('whois '. escapeshellarg( $arguments['d'] ), $output);
if( $code == 0 )
{
	foreach( $output as $line )
	{
		$line = strtolower($line);
		if( strpos( $line, 'renewal date' ) !== FALSE )
		{
			$line = explode(':', $line, 2);
			$now = new DateTime();
			$expiration_datetime = new DateTime( str_replace('.', '-',trim($line[1])));

			$difference = $now->diff($expiration_datetime);
			$difference = (int) $difference->format('%R%a');
			
			if( $difference < $days_critical_treshold )
			{
				fwrite(STDOUT, 'ERROR: Expires in '.$difference." days ago\n");
				exit(2);
			}
			elseif( $difference < $days_warning_treshold )
			{
				fwrite(STDOUT, 'WARNING: Expires in '.$difference." days\n");
				exit(1);
			}
			else
			{
				fwrite(STDOUT, 'OK: Expires in '.$difference." days\n");
				exit(0);
			}
			
			//echo $datetime->format('Y-m-d, H:i:s');
		}
	}
	
	// Assumes there were no exit
	fwrite(STDOUT, "WARNING: renewal date not found\n");
}
else
{
	fwrite(STDOUT, 'Whois returned code '.$code."\n");
}

exit(3);