#!/usr/bin/env php
<?php
define("DEFAULT_IP_ADDRESS","127.0.0.1");
define("HOSTSFILE","/etc/hosts");
define("SECTIONSTART","myhost_start");
define("SECTIONEND","myhost_end");

$params = $argv;
if(!isset($params[1])){
	echo "Usage myhosts [<action>] <hostname> [<ip>]\n";
	die();
}
$action = isset($params[1]) && isset($params[2])?$params[1]:($params[1]=="list"?"list":'add');
$hostname = isset($params[2])?$params[2]:($params[1]=="list"?"":$params[1]);
$ip = isset($params[3])?$params[3]:DEFAULT_IP_ADDRESS;

$hosts_str = file_get_contents(HOSTSFILE);
$pattern = "/\#".SECTIONSTART."(.*)\#".SECTIONEND."/is";

preg_match($pattern,$hosts_str,$match);

$hosts_modified = isset($match[1])?$match[1]:"";
$hosts_original = isset($match[0])?str_replace($match[0],"",$hosts_str):$hosts_str;
$hosts_modified_array = explode("\n",$hosts_modified);

switch($action){
	case "add" :
		echo "\e[0;30;42mAdding ".$ip." ".$hostname."\e[0m\n";
		$hosts_modified_array[] = $ip." ".$hostname;
		array_unshift($hosts_modified_array,"#".SECTIONSTART);
		$hosts_modified_array[].="#".SECTIONEND;
		$hosts_modified_array	= array_filter($hosts_modified_array,function($var){return !empty($var) && strlen($var)>0 && ($var != "\n");});
		$hosts_modified = implode("\n",$hosts_modified_array);
		$hosts_new = $hosts_original."\n".$hosts_modified;
		$f = fopen(HOSTSFILE,"w");
		fwrite($f,$hosts_new);
		fclose($f);
	break;
	case "list":
		echo "\e[0;30;42mListing\e[0m\n";
		foreach($hosts_modified_array as $h){
			echo $h."\n";
		}
	break;
	case "delete":
		echo "\033[41;30mDeleting $hostname \033[40;37m\r\n";
                for($i=0;$i<count($hosts_modified_array)-1;$i++){
			$hma = explode(" ",$hosts_modified_array[$i]);
			if(isset($hma[1])){
				unset($hosts_modified_array[$i]);
			}
		}
		array_unshift($hosts_modified_array,"#".SECTIONSTART);
                $hosts_modified_array[].="#".SECTIONEND;
                $hosts_modified_array   = array_filter($hosts_modified_array,function($var){return !empty($var) && strlen($var)>0 && ($var != "\n");});

		$hosts_modified = implode("\n",$hosts_modified_array);
                $hosts_new = $hosts_original."\n".$hosts_modified;
                $f = fopen(HOSTSFILE,"w");
                fwrite($f,$hosts_new);
                fclose($f);

	break;
	default:
	break;
}

echo "\naction : $action , hostname : $hostname , ip = $ip \n";
