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

#
# Simple script to change color of vtenext using some standard values
# The purpose is to quickly change color of an environment to differentiate 
# it from the production.
#
VERSION="1.1"

#
# Changelog
#
# Version 1.1
#  - Some cleanup
#
# Version 1.0
#  - First version
#


# CONSTANTS

DEBUG_LEVEL_DEBUG=4
DEBUG_LEVEL_INFO=3
DEBUG_LEVEL_WARNING=2
DEBUG_LEVEL_ERROR=1
RETCODE_OK=0
RETCODE_FAIL=1
RETCODE_BREAK=2
RETCODE_OKROLLBACK=3


# CONFIG VARIABLES

[ -t 1 ] && USECOLORS=1 || USECOLORS=0
DEBUG=$DEBUG_LEVEL_INFO
VTEDIR=../
COLOR=""


# FUNCTIONS

print_text () {
	echo "$*"
}

debug () {
	[ "$DEBUG" -ge $DEBUG_LEVEL_DEBUG ] && print_text "${COLOR_WHITE}[DEBUG]${COLOR_NORMAL} $1"
}

info () {
	[ "$DEBUG" -ge $DEBUG_LEVEL_INFO ] && print_text "${COLOR_CYAN}[INFO]${COLOR_NORMAL} $1"
}

warning () {
	[ "$DEBUG" -ge $DEBUG_LEVEL_WARNING ] && print_text "${COLOR_YELLOW}[WARNING]${COLOR_NORMAL} $1"
}

error () {
	[ "$DEBUG" -ge $DEBUG_LEVEL_ERROR ] && print_text "${COLOR_RED}[ERROR]${COLOR_NORMAL} $1"
}

check_command () {
	debug "Checking $1..."
	command -v "$1" > /dev/null 2>&1 || { error "Command $1 not found."; exit $RETCODE_FAIL; }
}

init_colors () {
	# first set all colors to 0
	COLOR_BOLD=""
	COLOR_UNDERLINE=""
	COLOR_STANDOUT=""
	COLOR_NORMAL=""
	COLOR_BLACK=""
	COLOR_RED=""
	COLOR_GREEN=""
	COLOR_YELLOW=""
	COLOR_BLUE=""
	COLOR_MAGENTA=""
	COLOR_CYAN=""
	COLOR_WHITE=""
	
	if [ $USECOLORS -eq 0 ]; then
		return
	fi
	
	# then check if we are using a real terminal and get the color codes
	command -v "tput" > /dev/null 2>&1 && [ -t 1 ]; { 
		local NCOL=$(tput colors)
		if [ -n "$NCOL" -a $NCOL -ge 8 ]; then
			COLOR_BOLD="$(tput bold)"
			COLOR_UNDERLINE="$(tput smul)"
			COLOR_STANDOUT="$(tput smso)"
			COLOR_NORMAL="$(tput sgr0)"
			COLOR_BLACK="$(tput setaf 0)"
			COLOR_RED="$(tput setaf 1)"
			COLOR_GREEN="$(tput setaf 2)"
			COLOR_YELLOW="$(tput setaf 3)"
			COLOR_BLUE="$(tput setaf 4)"
			COLOR_MAGENTA="$(tput setaf 5)"
			COLOR_CYAN="$(tput setaf 6)"
			COLOR_WHITE="$(tput setaf 7)"
		fi
	}
}

print_usage () {
	cat << USAGE
Usage: changeColor [OPTIONS...] COLOR

COLOR can be any of the following:
    red, green, yellow, orange, brown, grey

Options
    -v N, --verbosity=N       Set the verbositiy level to N (1=errors only, 4=debug, default=3)
          --version           Show version number
    -h,   --help              Show this help screen
    
USAGE
	
	exit $RETCODE_OK
}

parse_cmdline () {
	while getopts ":hv:-:" arg; do
		case $arg in
			# special case for long options
			-)
				# split the value from the name
				local LONGOPT="$OPTARG"
				if [[ "$OPTARG" =~ = ]] ; then
					LONGOPT="${OPTARG%%=*}"
					OPTARG="${OPTARG##*=}"
				else
					OPTARG=""
				fi
				
				case "$LONGOPT" in
					verbosity)
						if [ -z "$OPTARG" ]; then
							echo "Missing argument for option --$LONGOPT"
							print_usage
						fi
						DEBUG="$OPTARG"
						;;
					version)
						echo "Vtenext color changer -- version $VERSION"
						exit $RETCODE_OK
						;;
					help)
						print_usage
						;;
					*)
						echo "Invalid argument: --$LONGOPT"
						print_usage
						;;
				esac
				;;
			# other options
			h)
				print_usage
				;;
			v)
				if [ -z "$OPTARG" ]; then
					echo "Missing argument for option --$arg"
					print_usage
				fi
				DEBUG="$OPTARG"
				;;
			?)
				echo "Invalid argument: -$OPTARG"
				print_usage
				;;
		esac
    done
    # now parse 
    shift $((OPTIND-1))
	COLOR="$1"
	case "$COLOR" in
		red|orange|green|yellow|brown|grey)
			# all good
			;;
		'')
			# no color passed
			print_usage
			;;
		*)
			error "Unsupported color $COLOR"
			exit $RETCODE_FAIL
	esac
}

check_sass () {
	command -v "sass" > /dev/null 2>&1 || { 
		info "Installing SASS command"
		apt install -y ruby ruby-dev ruby-ffi
		gem install sass
	}
}

change_color () {

	# use some nice colors
	case $COLOR in
		green)
			# nothing, hmtl green is fine
			;;
		red)
			COLOR="#c73003"
			;;
		orange)
			COLOR="#dba01b"
			;;
		brown)
			COLOR="#785401"
			;;
		yellow)
			COLOR="#deeb11"
			;;
		grey)
			# also grey is fine
			;;
	esac
	
	if [ -d $VTEDIR"themes/next/" ]; then
		apply_theme_change next
	fi
	
	if [ -d $VTEDIR"themes/next22/" ]; then
		apply_theme_change next22
	fi
	
	rebuild_resources
}

apply_theme_change () {
	# $1 = theme
	
	info "Changing $1 theme..."
	local THEMEDIR="$VTEDIR"themes/"$1"/
	local COLORFILE="$THEMEDIR"scss/vars/_colors.scss
	
	sed -i 's/\$vte-primary:.*/$vte-primary: '$COLOR' !default;/g' -- $COLORFILE
	sed -i 's/\$vte-text-title:.*/$vte-text-title: '$COLOR' !default;/g' -- $COLORFILE
	sed -i 's/\$vte-text-record:.*/$vte-text-record: '$COLOR' !default;/g' -- $COLORFILE
	sed -i 's/\$vte-menusep:.*/$vte-menusep: '$COLOR' !default;/g' -- $COLORFILE
	pushd "$THEMEDIR" >/dev/null
		
	if [ -f compile_css.sh ]; then
		chmod 755 compile_css.sh
		./compile_css.sh
	elif [ -f compile.sh ]; then
		chmod 755 compile.sh
		./compile.sh
	else
		error "No compile script found for theme $1"
	fi
	
	popd >/dev/null
}

rebuild_resources () {
	info "Rebuilding resources..."
	
	pushd "$VTEDIR" >/dev/null
	
	cat << 'REBUILD' > rebuildres.php
<?php
require('config.inc.php');
require_once('include/utils/utils.php');
$RV = ResourceVersion::getInstance();
$RV->enableCacheWrite();
$RV->updateResources();
REBUILD

	php -f rebuildres.php
	rm -f rebuildres.php

	popd >/dev/null
	
}
# ------------------------ START ------------------------


# command line parsing
parse_cmdline "$@"


# color init and header
init_colors
print_text "${COLOR_BOLD}${COLOR_WHITE}Vtenext color changer  -- version $VERSION ${COLOR_NORMAL}"

if [ -z "$COLOR" ]; then
	print_usage
fi

check_command sed
check_command php

check_sass

change_color

