<?php
/*!
 * Host 初始化脚本
**/
anmp_log('EXEC FILE   [AnmpReload.host.php]');


// 注入配置变量
$ANMP_ROOT = ANMP_ROOT;
$_ENV['ANMP_SITE_DIRS'] = array();
$_ENV['ANMP_HOST_DIRS'] = array();
$_ENV['ANMP_HOST_DIRS_SYS']  = glob(ANMP_ROOT.'/www/htdocs/*.*' , GLOB_ONLYDIR);
$_ENV['ANMP_HOST_DIRS_USER'] = glob(ANMP_HTDOCS.'/*.*' , GLOB_ONLYDIR);

if (is_array($_ENV['ANMP_HOST_DIRS_SYS'])) {
	$_ENV['ANMP_HOST_DIRS'] = $_ENV['ANMP_HOST_DIRS_SYS'];
}
if (is_array($_ENV['ANMP_HOST_DIRS_USER'])) {
	$_ENV['ANMP_HOST_DIRS'] = array_merge($_ENV['ANMP_HOST_DIRS'], $_ENV['ANMP_HOST_DIRS_USER']);
}

print_r($_ENV['ANMP_HOST_DIRS']);

$_ENV['ANMP_HOST_OLD_FILE'] = glob(ANMP_ROOT.'/conf/httpd-vhosts/httpd-{n,c}*' , GLOB_BRACE);
foreach ($_ENV['ANMP_HOST_OLD_FILE'] as $old) {
	unlink($old);
}

// print_r($_ENV);

foreach ($_ENV['ANMP_HOST_DIRS'] as $key => $dir)
{
	$domain = strtolower(basename($dir));
	$doname = implode('.', array_reverse(explode('.', $domain)));
	$_STR   = <<<EOT
# http://{$domain}
# name: httpd-{$doname}.conf\n
# http://{$domain}
<VirtualHost *:80>
	ServerName   {$domain}
	DocumentRoot "{$dir}"
	ErrorLog     "{$ANMP_ROOT}/data/logs/{$doname}-error.log"
	CustomLog    "{$ANMP_ROOT}/data/logs/{$doname}-common.log" common
	php_admin_value open_basedir "{$ANMP_ROOT}/data/temp;{$dir}"
</VirtualHost>\n\n
EOT;

	$sdirs = glob($dir.'/*.*.*' , GLOB_ONLYDIR);
	foreach ($sdirs as $skey => $sdir) {
		$sdomain = strtolower(basename($sdir));
		$sdoname = implode('.', array_reverse(explode('.', $sdomain)));
		$_STR   .= <<<EOT
# http://{$sdomain}
<VirtualHost *:80>
	ServerName   {$sdomain}
	ServerAlias  *.{$sdomain}
	DocumentRoot "{$sdir}"
	ErrorLog     "{$ANMP_ROOT}/data/logs/{$doname}-error.log"
	CustomLog    "{$ANMP_ROOT}/data/logs/{$doname}-common.log" common
	php_admin_value open_basedir "{$ANMP_ROOT}/data/temp;{$sdir}"
</VirtualHost>\n\n
EOT;
	}

	// 写入新虚拟主机配置文件
	file_put_contents("{$ANMP_ROOT}/conf/httpd-vhosts/httpd-{$doname}.conf", $_STR . "# END");
}


// 更新默认主机配置文件
$httpd_default_file    = ANMP_ROOT."/conf/httpd-vhosts/httpd-00.default.conf";
$httpd_default_content = file_get_contents("{$httpd_default_file}.tpl");
$httpd_default_content = str_replace('{$ANMP_ROOT}',   ANMP_ROOT, $httpd_default_content);
$httpd_default_content = str_replace('{$ANMP_HTDOCS}', ANMP_HTDOCS, $httpd_default_content);
if (is_dir(ANMP_HTDOCS)) {
	$httpd_default_content = str_replace('>= 2.5', '<= 2.5', $httpd_default_content);
}

file_put_contents($httpd_default_file, $httpd_default_content);



//END