<?php

if ($_SERVER["HTTP_HOST"] && substr($_SERVER["HTTP_HOST"], 0, 3) != "dev") {
	echo "Invalid Environment!";
	exit;
}

define('WE_VERSION', '1.0.0');

$conf = array(
	'common',
	'component',
	'business',
	'page',
);

require('CSSMin.php');

if ($_SERVER["HTTP_HOST"]) $is_web = true;
else $is_web = false;

define('DS', DIRECTORY_SEPARATOR);
define('ROOT_DIR' , dirname(__FILE__) . DS . '..');
define('SRC_DIR' , ROOT_DIR . DS . 'src');
define('COMPRESS_DIR_NAME', ROOT_DIR . DS . 'compressed');
if ($is_web) define('LINE', "<br />");
else define('LINE', "\n");

function we_compress_css($conf) {
	$str = '';
	$full_str = '';

	// 优先加载 reset.css
	$str .= CSSMin::minify(file_get_contents(SRC_DIR . DS . 'common/reset.css'));
	$full_str = file_get_contents(SRC_DIR . DS . 'common/reset.css') . LINE;
	echo 'reset.css : compressed' . LINE;
	flush();
    ob_flush();

	foreach ($conf as $path) {
		$filepath = SRC_DIR . DS . $path;

		if( $handle  = opendir($filepath) ) {
			while( false !== ( $fileName = readdir($handle) ) ) {
				if ($path == 'common' && $fileName == 'reset.css') {
					continue;
				}
				if(strpos($fileName, '.css')) {
					$file = $filepath . DS . $fileName;

					if (is_file($file)) {
						$file_str = file_get_contents($file);
						//CSSMin一下
						$str .= CSSMin::minify($file_str);
						$full_str .= $file_str . LINE;
						
						echo $file . ' : compressed' . LINE;
						flush();
    					ob_flush();
					}
				}
			}
			closedir($handle);
		}
	}

	//去除多余的 @charset "utf-8";
	$str = '@charset "utf-8";' . str_replace('@charset "utf-8";', '', $str);					
	$full_str = '@charset "utf-8";' . str_replace('@charset "utf-8";', '', $full_str);
				
	//改变img路径
	$str = preg_replace("/(\.\.\/)+img\//i", '../../img/', $str);
	$full_str = preg_replace("/(\.\.\/)+img\//i", '../../img/', $full_str);

	//增加版本号
	$version = time();
	$str = preg_replace("/(url\(.*?)\)/i", "$1?v=".$version.")", $str);
	$full_str = preg_replace("/(url\(.*?)\)/i", "$1?v=".$version.")", $full_str);


	$bFull = file_put_contents(COMPRESS_DIR_NAME . DS . 'we-' . WE_VERSION . '.css', $full_str);
	$bStr = file_put_contents(COMPRESS_DIR_NAME . DS . 'we-' . WE_VERSION . '.min.css', $str);
	if ($bFull && $bStr) {
		echo 'we-' . WE_VERSION . '.css compressed!' . LINE;
		flush();
	    ob_flush();
	} else {
		echo "Error! 可能是权限设置的问题!".LINE;
		flush();
	    ob_flush();
	    exit;
	}

	system('svn ci -m "compress css by scripts" '.COMPRESS_DIR_NAME);
	system('svn up '.ROOT_DIR."/..");
}
if ($is_web) {
	echo str_pad('Compressing... ',4096).LINE;
}
we_compress_css($conf);

if ($is_web) {
	echo 
	'<h2>请稍等,即将开始重新Build JS</h2>
	<script type="text/javascript">
		setTimeout(function() {
			window.location.href = "/common/js/tools/refresh.php";
		}, 1500);
	</script>';
	flush();
	ob_flush();	
} else {
	echo "Start rebuild js...".LINE;
	system("php ".ROOT_DIR."/../js/tools/refresh.php");
}