#!/usr/bin/env php
<?php
if (!isset($argv[1]) || $argv[1] == 'help' || $argv[1] == '--help' || $argv[1] == '-h')
	die("Usage: 
  phpquery URL --method1 arg1 arg2 argN --method2 arg1 arg2 argN ...
Example: 
  phpquery 'http://localhost' --find 'div > p' --contents
Pipe: 
  cat index.html | phpquery --find 'div > p' --contents
Docs: 
  http://code.google.com/p/phpquery/wiki/\n");
/* ALL-IN-ONE-SECTION-START */
set_include_path(get_include_path()
	.':'.'/usr/lib/phpquery'
	.':'.realpath(dirname(__FILE__).'/../phpQuery')
);
require_once('phpQuery.php');
/* ALL-IN-ONE-SECTION-END */
//phpQuery::$debug = true;
//var_dump($argv);
if (isset($argv[1]) && parse_url($argv[1], PHP_URL_HOST)) {
	if (@include_once('Zend/Http/Client.php')) {
		// use Ajax if possible
		phpQuery::ajaxAllowURL($argv[1]);
		// TODO support contentType passing (from response headers)
		phpQuery::get($argv[1],
			new Callback('phpQueryCli', new CallbackParam, array_slice($argv, 2))
		);
	} else {
		// use file wrapper when no Ajax
		phpQueryCli(file_get_contents($argv[1]), array_slice($argv, 2));
	}
} else if (feof(STDIN) === false) {
	$markup = '';
	while(!feof(STDIN))
		$markup .= fgets(STDIN, 4096);
	phpQueryCli($markup, array_slice($argv, 1));
} else {
	phpQueryCli($argv[1], array_slice($argv, 2));
}
function phpQueryCli($markup, $callQueue) {
	$pq = phpQuery::newDocument($markup);
	$method = null;
	$params = array();
	foreach($callQueue as $param) {
		if (strpos($param, '--') === 0) {
			if ($method) {
				$pq = call_user_func_array(array($pq, $method), $params);
			}
			$method = substr($param, 2);	// delete --
			$params = array();
		} else {
			$param = str_replace('\n', "\n", $param);
			$params[] = strtolower($param) == 'null'
				? null
				: $param;
		}
	}
	if ($method)
		$pq = call_user_func_array(array($pq, $method), $params);
	if (is_array($pq))
		foreach($pq as $v)
			print $v;
	else
		print $pq."\n";
	//var_dump($pq);
}
?>