#!/usr/bin/php
<?php
/*
  vim: set expandtab tabstop=4 softtabstop=4 shiftwidth=4:
  Codificación: UTF-8
  +----------------------------------------------------------------------+
  | Elastix version 2.0                                                  |
  | http://www.elastix.org                                               |
  +----------------------------------------------------------------------+
  | Copyright (c) 2006 Palosanto Solutions S. A.                         |
  +----------------------------------------------------------------------+
  | Cdla. Nueva Kennedy Calle E 222 y 9na. Este                          |
  | Telfs. 2283-268, 2294-440, 2284-356                                  |
  | Guayaquil - Ecuador                                                  |
  | http://www.palosanto.com                                             |
  +----------------------------------------------------------------------+
  | The contents of this file are subject to the General Public License  |
  | (GPL) Version 2 (the "License"); you may not use this file except in |
  | compliance with the License. You may obtain a copy of the License at |
  | http://www.opensource.org/licenses/gpl-license.php                   |
  |                                                                      |
  | Software distributed under the License is distributed on an "AS IS"  |
  | basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See  |
  | the License for the specific language governing rights and           |
  | limitations under the License.                                       |
  +----------------------------------------------------------------------+
  | The Original Code is: Elastix Open Source.                           |
  | The Initial Developer of the Original Code is PaloSanto Solutions    |
  +----------------------------------------------------------------------+
  $Id: verify_rpm,v 0.0.1 2013/11/26 11:31:12 Luis Abarca Exp $
*/
/*
exec("pear list Console_CommandLine",$output,$retval);
$pattern="/`Console_CommandLine' not installed/";
if ((preg_match($pattern,$output[1]))){
	system("pear install Console_CommandLine",$retval);
	handlingErrors($retval,"Succesfully Installed 'Console_CommandLine'.","Verify the instalation of pear package 'Console_CommandLine' before use this script.");
}
*/
//var_dump($argc);
//if ($argc > 1){
//require_once 'Console/CommandLine.php';
require_once 'Console/Getopt.php';
/*
$parser = new Console_CommandLine();
$parser->description = 'Script in charge of create a report of Version and Release of Elastix and Addons rpm installed in the system.';
$parser->version = '0.0.1';

$parser->addOption('onlyone', array(
    'short_name'  => '-o',
    'long_name'   => '--only-one',
    'help_name'	  => 'rpm',
    'description' => 'It generates the status of the rpm wich name is given.',
    'action'     => 'StoreTrue',
));

$parser->addOption('listall', array(
    'short_name'  => '-a',
    'long_name'   => '--listall',
    'description' => 'List All rpms that are in rpm_availables file wheter are installed or not .',
    'action'     => 'StoreTrue',
));

$parser->addOption('listinstalled', array(
    'short_name'  => '-l',
    'long_name'   => '--installed',
    'description' => 'List only the rpms that are currently installed in your system.',
    'action'      => 'StoreTrue'
));

$parser->addOption('notinstalled', array(
    'short_name'  => '-n',
    'long_name'   => '--not-installed',
    'description' => 'List only the rpms that are not currently installed in your system.',
    'action'      => 'StoreTrue'
));

$parser->addArgument(
    'rpm',
    array(
        'multiple' => false,
        'description' => 'name of rpm to find the respectively status',
	'optional' => true
    )
);

try {
	global $result;
    $result = $parser->parse();
		
		#o
		if (($result->options['onlyone'] == TRUE)&&($result->options['listall'] == FALSE)&&($result->options['listinstalled'] == FALSE)&&($result->options['notinstalled'] == FALSE)){
				//printf ("Procediendo a mostrar status de: ".$argv[2].PHP_EOL);
				onlyone($argv[2]);				
		}
		
		#a
		if (($result->options['onlyone'] == FALSE)&&($result->options['listall'] == TRUE)&&($result->options['listinstalled'] == FALSE)&&($result->options['notinstalled'] == FALSE)){
				//printf ("Procediendo a mostrar status de todos los rpms Elastix y Addons ".PHP_EOL);
				listall();	
		}
		
		#l
		if (($result->options['onlyone'] == FALSE)&&($result->options['listall'] == FALSE)&&($result->options['listinstalled'] == TRUE)&&($result->options['notinstalled'] == FALSE)){
				//printf ("Procediendo a mostrar status de solos los rpms Elastix y Addons instalados en el sistema".PHP_EOL);
				listexclusive("installed");
		}
		
		#n
		if (($result->options['onlyone'] == FALSE)&&($result->options['listall'] == FALSE)&&($result->options['listinstalled'] == FALSE)&&($result->options['notinstalled'] == TRUE)){
				//printf ("Procediendo a mostrar status de los rpms Elastix y Addons que no estan instalados en el sistema".PHP_EOL);
				listexclusive("notinstalled");
		}

		if (($result->options['onlyone'] == FALSE)&&($result->options['listall'] == FALSE)&&($result->options['listinstalled'] == FALSE)&&($result->options['notinstalled'] == FALSE)){
			#print("\nThere is no parameter.\n".PHP_EOL);
			$parser->displayUsage();
			print_r($result->options);
   			print_r($result->args);		
		}

		#restrict combinations
		#all activated
		#0011
		if (($result->options['onlyone'] == FALSE)&&($result->options['listall'] == FALSE)&&($result->options['listinstalled'] == TRUE)&&($result->options['notinstalled'] == TRUE)){
			general_error();
		}
		#0110
		if (($result->options['onlyone'] == FALSE)&&($result->options['listall'] == TRUE)&&($result->options['listinstalled'] == TRUE)&&($result->options['notinstalled'] == FALSE)){
			general_error();
		}
		#0111
		if (($result->options['onlyone'] == FALSE)&&($result->options['listall'] == TRUE)&&($result->options['listinstalled'] == TRUE)&&($result->options['notinstalled'] == TRUE)){
			general_error();
		}
		#1001
		if (($result->options['onlyone'] == TRUE)&&($result->options['listall'] == FALSE)&&($result->options['listinstalled'] == FALSE)&&($result->options['notinstalled'] == TRUE)){
			general_error();
		}
		#1010
		if (($result->options['onlyone'] == TRUE)&&($result->options['listall'] == FALSE)&&($result->options['listinstalled'] == TRUE)&&($result->options['notinstalled'] == FALSE)){
			general_error();
		}
		#1011
		if (($result->options['onlyone'] == TRUE)&&($result->options['listall'] == FALSE)&&($result->options['listinstalled'] == TRUE)&&($result->options['notinstalled'] == TRUE)){
			general_error();
		}
		#1100	
		if (($result->options['onlyone'] == TRUE)&&($result->options['listall'] == TRUE)&&($result->options['listinstalled'] == FALSE)&&($result->options['notinstalled'] == FALSE)){
			general_error();
		}
		#1101
		if (($result->options['onlyone'] == TRUE)&&($result->options['listall'] == TRUE)&&($result->options['listinstalled'] == FALSE)&&($result->options['notinstalled'] == TRUE)){
			general_error();
		}
		#1110
		if (($result->options['onlyone'] == TRUE)&&($result->options['listall'] == TRUE)&&($result->options['listinstalled'] == TRUE)&&($result->options['notinstalled'] == FALSE)){
			general_error();
		}
		#1111
		if (($result->options['onlyone'] == TRUE)&&($result->options['listall'] == TRUE)&&($result->options['listinstalled'] == TRUE)&&($result->options['notinstalled'] == TRUE)){
			general_error();
		}
		
		
} catch (Exception $exc) {
    $parser->displayError($exc->getMessage());
}*/
/*}else{
	print("There is no parameter ".PHP_EOL);
	//onlyone($argv[2]);
}*/


#var_dump($argv);
#print($argv['2'].PHP_EOL);

if ( ($argv['1'] == "--onlyone") && (empty($argv['2'])) ){
	error_exit("No action specified (--onlyone or --listall or --installed or --notinstalled)\n");
}

// Parse command-line options
$opt = Console_Getopt::getopt($argv, '', array(
    'onlyone',     // prepare passwords for first-time use
    'listall',   // change existing set of passwords
    'installed',     // prepare passwords for first-time use
    'notinstalled',   // change existing set of passwords
));

//var_dump($argv);

if (PEAR::isError($opt)) error_exit($opt->getMessage()."\n");
//validateOptions($opt);
foreach ($opt[0] as $option) switch ($option[0]) {
case '--onlyone':
    exit(action_onlyone($opt,$argv['2']) ? 0 : 1);
case '--listall':
    exit(action_listall($opt) ? 0 : 1);
case '--installed':
    exit(listexclusive($opt,"installed") ? 0 : 1);
case '--notinstalled':
    exit(listexclusive($opt,"notinstalled") ? 0 : 1);
default:
    error_exit("No action specified (--onlyone or --listall or --installed or --notinstalled)\n");
break;
}
error_exit("No action specified (--onlyone or --listall or --installed or --notinstalled)\n");

/************/
/*FUNCTIONS*/
/***********/

function error_exit($sMsg, $errorcode = 1){
    fwrite(STDERR, $sMsg);
    exit($errorcode);
}

function handlingErrors($val,$msgG,$msgW){
    if ($val <> FALSE){
        exit("\n$msgW".PHP_EOL);
    }else{
        printf("\n$msgG.".PHP_EOL);
    }
}

function general_error(){
	print("It cant be use in this way. Use it with only one option at the time.".PHP_EOL);
}

function rpmquery(){
	$dirbase="/var/www/db";
	$list_rpms=file($dirbase."/rpms_availables");
	/*foreach( $list_rpms as $lrpm ){
		exec("rpm -q --queryformat 'Name:%{NAME} Version:%{VERSION} Release:%{RELEASE}' $lrpm",$output,$retval);
	}*/
	exec("rpm -q --queryformat 'N:%{NAME} V:%{VERSION} R:%{RELEASE}\n' `cat $dirbase/rpms_availables`",$output,$retval);
	return $output;
}

function action_onlyone($opt,$rpm){
	/*if( (empty($rpm)) || ( $argc < "2") ){
		error_exit("No action specified (--onlyone or --listall or --installed or --notinstalled)\n");
	}*/
	system("rpm -q --queryformat 'N:%{NAME} V:%{VERSION} R:%{RELEASE}\n' ".$rpm,$retval);
}

function action_listall($opt){
//$dirbase="/root";
//$list_rpms=file($dirbase."/rpms_availables");
/*
foreach( $list_rpms as $lrpm ){
	exec("rpm -q --queryformat 'Name:%{NAME} Version:%{VERSION} Release:%{RELEASE}' $lrpm",$output,$retval);
}*/
	/*
	foreach($output as $out){
		print("$out\n");
	}*/
	//$pattern="/Name:([a-zA-Z0-9_-]{1,}+)/";
	$output=rpmquery();
	foreach($output as $out){
		print($out.PHP_EOL);
	}

}

function listexclusive($opt,$option){
	//$pattern="/Name:([[:word:][:blank:][:punct:]ñÑáéíóúÁÉÍÓÚ]+)\sVersion:([[:word:][:blank:][:punct:]ñÑáéíóúÁÉÍÓÚ]+)\sRelease:([[:word:][:blank:][:punct:]ñÑáéíóúÁÉÍÓÚ]+)/";
	$pattern="/N:([[:word:][:blank:][:punct:]ñÑáéíóúÁÉÍÓÚ]+)\sV:([[:word:][:blank:][:punct:]ñÑáéíóúÁÉÍÓÚ]+)\sR:([[:word:][:blank:][:punct:]ñÑáéíóúÁÉÍÓÚ]+)/";
	$output=rpmquery();
	foreach( $output as $out ){
		switch ($option){
			case "installed":
				if ((preg_match($pattern,$out))){
					$out1[] = $out;
					//print("Entre $out1\n");
					//var_dump($out1);
				}
			break;

			case "notinstalled":
				if (!(preg_match($pattern,$out))){
					$out1[] = $out;
					//print("Entre $out1\n");
					//var_dump($out1);
				}
			break;
		}
	}
		foreach($out1 as $out2){
			print($out2.PHP_EOL);
		}
}
?>
