#!/usr/bin/env php
<?php
/*************************************
 * SPDX-FileCopyrightText: 2009-present Vtenext S.r.l. Società Benefit 
 * SPDX-License-Identifier: LicenseRef-vtenext-business-license 
 ************************************/

// crmv@311464

$moduleIconsGen = new VtenextModuleIconsGenerator();

require(__DIR__ . '/../config.inc.php');
if (empty($root_directory)) return $moduleIconsGen->error("Vtenext not installed");

chdir($root_directory);
require_once('include/utils/utils.php');

$moduleIconsGen->go();

class VtenextModuleIconsGenerator {

	public $version = '1.0';
	
	public $config = [
		'loglevel' => 4, // 1 = fatal, 2 = error, 3 = warning, 4 = info, 5 = debug
		'generated_dir' => 'themes/next22/scss/vars/generated/',
		'generated_file' => '_module_icons.scss',
		'themes_to_compile' => [
			'next22' => 'compile.sh',
		],
	];
	
	public function go() {
		$this->initTool();
		
		return $this->generate();
	}
	
	protected function generate() {
		if (!$this->checkSass()) {
			$this->error("Sass not installed, please refer to http://sass-lang.com/install for the installation guide.");
			exit(1);
		}
		
		if (!is_dir($this->config['generated_dir'])) {
			if (!mkdir($this->config['generated_dir'], 0755, true)) {
				$this->error("Unable to create directory for generated file.");
				exit(1);
			}
		}
		
		$contents = $this->makeFileContents();
		
		$success = file_put_contents($this->config['generated_dir'].$this->config['generated_file'], $contents);
		
		if ($success === false || !file_exists($this->config['generated_dir'].$this->config['generated_file'])) {
			$this->error("Write generated_file failed.");
			exit(1);
		} else {
			$this->info("File ".$this->config['generated_dir'].$this->config['generated_file']." generated");
		}
		
		$this->compileThemes();
		
		$this->info("Done.");
	}
	
	protected function makeFileContents() {
		global $adb, $table_prefix;
		
		$vte_material_icons = [];
		$vte_material_icons_filled = [];
		$vte_fa_icons = [];
		
		$result = $adb->pquery("select * from {$table_prefix}_tab_info where prefname = ?", ['icon']);
		if ($result && $adb->num_rows($result) > 0) {
			while($row=$adb->fetchByAssoc($result,-1,false)) {
				
				$icon = Zend_Json::decode($row['prefvalue']);
				$modulename = strtolower(getTabName($row['tabid']));
				
				if ($icon['type'] == 'fa') {
					$vte_fa_icons[$modulename] = $icon['icon'];
				} elseif ($icon['type'] == 'material') {
					$vte_material_icons[$modulename] = $icon['icon'];
					if (isset($icon['options'])) {
						if ($icon['options']['filled']) {
							$vte_material_icons_filled[] = $modulename;
						}
					}
				}
			}
		}
		
		$contents = '';
		
		$contents .= "// https://fonts.google.com/icons\n";
		$contents .= '$vte-material-icons: ('."\n";
		foreach($vte_material_icons as $mod => $icon) {
			$contents .= "\t{$mod}: \"$icon\",\n";
		}
		$contents .= ');'."\n\n";

		$contents .= "// The list of modules using the filled style of the Material font\n";
		$contents .= '$vte-material-icons-filled: (';
		foreach($vte_material_icons_filled as $mod) {
			$contents .= "{$mod}, ";
		}
		$contents = rtrim($contents, ', ');
		$contents .= ');'."\n\n";
		
		$contents .= "// FontAwesome icon variables: fonts/font-awesome/font-awesome/_variables.scss\n";
		$contents .= "// https://fontawesome.com/v3/icons\n";
		$contents .= '$vte-fa-icons: ('."\n";
		foreach($vte_fa_icons as $mod => $icon) {
			$contents .= "\t{$mod}: \"$icon\",\n";
		}
		$contents .= ');';
		
		return $contents;
	}
	
	protected function initTool() {
		// enable error reporting
		error_reporting(E_ALL);
		ini_set('display_errors', 1);
		
		// check cli invocation
		if (php_sapi_name() != 'cli') return $this->error("Please execute from CLI");
		
		if (function_exists('pcntl_signal')) {
			// otherwise pipes in exec'd commands fails
			// see https://bugs.php.net/bug.php?id=51160
			pcntl_signal(SIGPIPE, function () {
				exit;
			});
		}
	}
	
	protected function checkSass() {
		/**
		 * Install on Debian/Ubuntu:
		 *
		 * as root:
		 * apt-get install rubygems
		 * gem install sass
		 * [optional] gem install compass
		 */
		return $this->checkCommand('sass');
	}
	
	protected function checkCommand($cmd) {
		$return = shell_exec(sprintf("which %s", escapeshellarg($cmd)));
		if (empty($return)) {
			return $this->error("Command not found: $cmd");
		}
		return true;
	}
	
	protected function compileThemes() {
		global $root_directory;
		
		if (!empty($this->config['themes_to_compile'])) {
			foreach($this->config['themes_to_compile'] as $theme => $compile_file) {
				$return = shell_exec("cd {$root_directory}themes/$theme && ./$compile_file");
				if (empty($return)) {
					return $this->error("Compile of theme $theme failed.");
				} else {
					$this->info("Theme $theme compiled");
				}
			}
		}
		return true;
	}
	
	protected function debug($msg) {
		if ($this->config['loglevel'] >= 5) {
			echo "[DEBUG] " . $msg . "\n";
		}
	}
	
	protected function info($msg) {
		if ($this->config['loglevel'] >= 4) {
			echo "[INFO] " . $msg . "\n";
		}
	}
	
	protected function warning($msg) {
		if ($this->config['loglevel'] >= 3) {
			echo "[WARNING] " . $msg . "\n";
		}
	}
	
	public function error($msg) {
		if ($this->config['loglevel'] >= 2) {
			if (php_sapi_name() == 'cli')
				echo "\e[31m[ERROR] " . $msg . "\e[0m\n";
			else
				echo "[ERROR] " . $msg . "\n";
		}
		exit(1);
	}
}
