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

/* crmv@333823 */
/*
 * Use this script to change the environment type of vte. Pass the type as the first parameter and after being changed,
 * all php scripts in plugins/envs/make.$envType/ will be executed
 */

$useColors = false; 
if (function_exists('posix_isatty') && posix_isatty(STDOUT)) {
	$useColors = true;
}

function error($msg) {
	global $useColors;
    $str = "\e[31m[ERROR]\e[0m ".$msg."\n";
	if (!$useColors) $str = stripAnsi($str);
	echo $str;
    exit(1);
}

function warning($msg) {
	global $useColors;
    $str = "\e[33m[ERROR]\e[0m ".$msg."\n";
	if (!$useColors) $str = stripAnsi($str);
	echo $str;
}

function info($msg) {
	global $useColors;
    $str = "\e[36m[INFO]\e[0m ".$msg."\n";
	if (!$useColors) $str = stripAnsi($str);
	echo $str;
}

/**
 * Remove ansi codes from string
 */
function stripAnsi(string $text) : string {
	$text = preg_replace('/\e[[][A-Za-z0-9];?[0-9]*m?/', '', $text);
	return $text;
}

// check cli invocation
if (php_sapi_name() != 'cli') error("Please execute from CLI");

$newType = $argv[1] ?? null;

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

if (empty($newType)) {
	error("Please specify the new type: prod, preprod, dev or debug");
}

if ($newType === $envType) {
	info("Enviroment Type is already $envType");
	exit;
}

if (!in_array($newType, ['prod', 'preprod', 'dev', 'debug'])) {
	error("Invalid type: $newType");
}

// all good, change the config
$conf = file_get_contents($config);
if (empty($conf)) {
	error("Unable to read config.inc.php");
}

$count = 0;
$conf = preg_replace('/\$envType\s*=\s*[\'"][a-z]+[\'"]\s*;/', "\$envType = '$newType';", $conf, -1, $count);

if ($count === 0) {
	// no replacements
	error("Unable to modify config.inc.php");
}

// write to a temp file (to also see if the root is writable)
$tempfile = __DIR__.'/../configtest.php';
if (!file_put_contents($tempfile, $conf)) {
	error("Unable to write temporary file");
}

// check if temporary file is syntactically valid
exec("php -l '$tempfile'", $out, $rescode);
if ($rescode !== 0) {
	error("The changed file has syntax errors. Aborting.");
}

// set permissions
chmod($tempfile, fileperms($config));
chown($tempfile, fileowner($config));
chgrp($tempfile, filegroup($config));

// copy original away
$bakfile = __DIR__.'/../config.inc.bak.php';
if (!copy($config, $bakfile)) {
	unlink($tempfile);
	error("Unable to create a backup copy of config.inc.php");
}

// rename temp
if (!rename($tempfile, $config)) {
	unlink($tempfile);
	unlink($bakfile);
	error("Unable to overwrite config.inc.php");
}

// remove backup
unlink($bakfile);

info("Enviroment Type set to \e[1m$newType\e[22m");

$scriptFolder = __DIR__."/../plugins/envs/make.$newType/";

if (is_dir($scriptFolder)) {
	
	$list = glob($scriptFolder.'*.*');
	$exec = [];
	foreach ($list as $file) {
		$fname = basename($file);
		$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
		if (($ext === 'php' || $ext === 'sh') && $fname !== "make.$newType.example.php") {
			if ($ext === 'sh' && !is_executable($file)) continue;
			$exec[] = $file;
		}
	}
	if (count($exec) > 0) {
		info("Executing scripts:");
		$count = 0;
		foreach ($exec as $file) {
			$fname = basename($file);
			$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
			echo "Executing $fname...\n";
			$rescode = 0;
			if ($ext === 'php') {
				$exec = "php $file";
			} else {
				$exec = "$file";
			}
			passthru("$exec $envType $newType", $rescode);
			if ($rescode !== 0) {
				warning("The script returned a non zero code.");
			}
			++$count;
		}
		info("Executed $count scripts");
	} else {
		info("No scripts to be executed");
	}
} else {
	warning("No folder found ($scriptFolder). No scripts will be executed");
	exit;
}
