#!/opt/local/bin/php
<?php

chdir('../..');
require_once 'common.php';

$tmp = array_slice(scandir(Config::get('app:Parser:bot_stats_dir')), 2);
$bots = array();
foreach ($tmp as $bfile) {
	$bots[str_replace('.json', '', $bfile)] = json_decode(file_get_contents(Config::get('app:Parser:bot_stats_dir').$bfile));
}
foreach ($bots as $name => $bot) {
	$tmp = exec("ps ".$bot->pid);
	$bot->active = (int) (strpos($tmp, strval($bot->pid)) !== false);
}

if (!isset($argv[1])) {
	echo "Bad action\n";
	die;
}

switch ($argv[1]) {
	case 'add':
		$bot_name = (isset($argv[2]) ? ucfirst($argv[2]) : false);
		if ($bot_name && isset($bots[$bot_name])) {
			$bot = $bots[$bot_name];
			if($bot->active) {
				echo $bot_name ." is working already\n";
			} else {
				echo "Launching ". $bot_name ."\n";
				shell_exec("./worker_html_grabber.php ". $bot_name ." > /www/parser_data/log/". $bot_name .".log &");
			}
		} else {
			$bots = custom_shuffle($bots);
			foreach ($bots as $name => $bot) {
				if (!$bot->active) {
					echo "Launching ". $name ."\n";
					shell_exec("./worker_html_grabber.php ". $name ." > /www/parser_data/log/". $name .".log &");
					die;
				}
			}
			echo "All bots are working already\n";
		}
		break;
	case 'retire':
		$bot_name = (isset($argv[2]) ? ucfirst($argv[2]) : false);
		if ($bot_name == 'all') {
			foreach ($bots as $name => $bot) {
				if ($bot->active) {
					echo "Stopping ". $name ."\n";
					shell_exec("kill ". $bot->pid);
				}
			}
		} elseif ($bot_name && isset($bots[$bot_name])) {
			$bot = $bots[$bot_name];
			if(!$bot->active) {
				echo $bot_name ." is not working now\n";
			} else {
				echo "Stopping ". $bot_name ."\n";
				shell_exec("kill ". $bot->pid);
			}
		} else {
			$bots = custom_shuffle($bots);
			foreach ($bots as $name => $bot) {
				if ($bot->active) {
					echo "Stopping ". $name ."\n";
					shell_exec("kill ". $bot->pid);
					die;
				}
			}
			echo "All bots are working already\n";
		}
		break;
	case 'list':
		foreach($bots as $name => $bot) {
			echo $name .': '. ($bot->active ? 'working' : 'down') ."\n";
		}
		break;
	default:
		echo "Bad action\n";
		break;
}

function custom_shuffle($my_array = array()) {
  $copy = array();
  while (count($my_array)) {
    $element = array_rand($my_array);
    $copy[$element] = $my_array[$element];
    unset($my_array[$element]);
  }
  return $copy;
}