#!/bin/bash

# Detect OS version 
dist=$(lsb_release -si)
ver=$(lsb_release -sr)
nam=$(lsb_release -sc)
tmpfile="/tmp/tmpfile"

# Detect hardware
cpu=$(pcs-cpu)
tmpfile="/tmp/tmpfile"

# Parameter "dev" to update webserver into a DEV machine 
if [ "-$1-" == "-dev-" ]; then
	src_path="$HOME/src/pcscale"
else
	src_path="/usr"
fi
# Update turn packages  (need internet connection)
turn=0
if [ "-$1-" == "-turn-" ]; then
	turn=1
fi

CheckPermission() {
	sf_path="/var/www/touchscale"
	if [ ! -d $sf_path ]; then
	        echo "Web server not installed! Can't update it."
	        exit 0
	fi
	account=`whoami`
	if [ ${account} != "root" ]; then
		echo " ${account}, you are NOT the supervisor."
		echo " The root permission is required to run this installer."
		echo " You must execute this script with sudo"
		exit 1
	fi
	echo Updating web app...
}

ConfigComposer() {
	ComposerJson="/var/www/touchscale/composer.json"
	modified="0"
	# test if exist "symlink" modification...
	grep -q "symfony-assets-install" $ComposerJson
	if [ $? -ne 0 ]; then
		sed '/symfony-web-dir/ a\        "symfony-assets-install": "symlink",' $ComposerJson > $tmpfile
		mv -f $tmpfile $ComposerJson
		modified="1"
	fi
	# if file modified...
	if [ "$modified" -ne "0" ]; then
		chown www-data:www-data $ComposerJson
		chmod g-w $ComposerJson
	fi
}

SetSymfonyConfig() {
	config="/var/www/touchscale/app/config/config.yml"
	mofified="0"
	# test if translation is activated...
	grep -q "#translator" $config
	if [ $? -eq 0 ]; then
		sed 's/#translator/translator/' $config > $tmpfile
		mv -f $tmpfile $config
		modified="1"
	fi
	# test if liip_theme is added...
	grep -q "liip_theme:" $config
	if [ $? -ne 0 ]; then
		echo ' ' >> $config
		echo 'liip_theme:' >> $config
		echo '    themes: ['web', 'tablet', 'phone']' >> $config
		echo '    active_theme: 'web'' >> $config
		echo '    autodetect_theme: true' >> $config

	fi
	if [ "$modified" -ne "0" ]; then
		chown www-data:www-data $config
		chmod g-w $config
	fi
}

SetSymfonyRouting() {
	routing_file="/var/www/touchscale/app/config/routing.yml"
	echo 'epelsa_pcscale:' > $routing_file
	echo '    resource: "@EpelsaPcscaleBundle/Resources/config/routing.yml"' >> $routing_file
	echo '    prefix:   /' >> $routing_file
	echo 'liip_theme:' >> $routing_file
	echo '    resource: "@LiipThemeBundle/Resources/config/routing.xml"' >> $routing_file
	echo '    prefix: /theme' >> $routing_file
	chown www-data:www-data $routing_file
}

UpdateSymfonySecurity() {
	config="/var/www/touchscale/app/config/security.yml"
	grep -q "/turns" $config
	if [ $? -eq 0 ]; then
	sed  -i '/            pattern:    ^\//c#            pattern    ^\/\n            pattern:    ^\/(?!(en|es|ca|fr|it)\/turns).*$/' $config
		sed -i '/pattern:    ^\//#pattern    ^\/\n        pattern:    ^/(?!(en|es|ca|fr|it)\/turns).*$/' $config
		mv -f $tmpfile $config
		chown www-data:www-data $config
		chmod g-w $config
	fi
}

RegisterSymfonyBundles() {
	AppKernel="/var/www/touchscale/app/AppKernel.php"
	mofified="0"
	# test if exist translation bundle...
	grep -q "JMSTranslationBundle" $AppKernel
	if [ $? -ne 0 ]; then
		sed '/SensioFrameworkExtraBundle/ a\            new JMS\\TranslationBundle\\JMSTranslationBundle(),' $AppKernel > $tmpfile
		mv -f $tmpfile $AppKernel
		modified="1"
	fi
	# test if exist theme bundle...
	grep -q "LiipThemeBundle" $AppKernel
	if [ $? -ne 0 ]; then
		sed '/JMSTranslationBundle/ a\            new Liip\\ThemeBundle\\LiipThemeBundle(),' $AppKernel > $tmpfile
		mv -f $tmpfile $AppKernel
		modified="1"
	fi
	# test if exist pcscale bundle...
	grep -q "EpelsaPcscaleBundle" $AppKernel
	if [ $? -ne 0 ]; then
		sed '/LiipThemeBundle/ a\            new Epelsa\\PcscaleBundle\\EpelsaPcscaleBundle(),' $AppKernel > $tmpfile
		mv -f $tmpfile $AppKernel
		modified="1"
	fi
	# if file modified...
	if [ "$modified" -ne "0" ]; then
		chown www-data:www-data $AppKernel
		chmod g-w $AppKernel
	fi
}

SetSymfonySecurity() {
	sec="/var/www/touchscale/app/config/security.yml"

	echo 'security:' > $sec
	echo '    encoders:' >> $sec
	echo '        Symfony\Component\Security\Core\User\User: plaintext' >> $sec
	echo ' ' >> $sec
	echo '    providers:' >> $sec
	echo '        in_memory:' >> $sec
	echo '            memory:' >> $sec
	echo '                users:' >> $sec
	echo '                    pcscale:  { password: epelsa, roles: [ 'ROLE_ADMIN' ] }' >> $sec
	echo ' ' >> $sec
	echo '    firewalls:' >> $sec
	echo '        secured_area:' >> $sec
	echo '            pattern:    ^/(?!(en|es|ca|fr|it|de)\/turns).*$' >> $sec
	echo '            anonymous: ~' >> $sec
	echo '            http_basic:' >> $sec
	echo '                realm: "Restricted Area"' >> $sec
	echo ' ' >> $sec
	echo '    access_control:' >> $sec
	echo '        - { path: ^/, roles: ROLE_ADMIN }' >> $sec
	chown www-data:www-data $sec
}

updatePHP54 () {
	add-apt-repository -y ppa:sergey-dryabzhinsky/php54
	apt-get update
}

WebServerUpdate() {
#	web_path="/usr/share/pcscale/Epelsa"
#	if [ -d $web_path ]; then
#		ln -sf $web_path /var/www/touchscale/src
#		# link to pcscale ".mo" files
#		# rm -f $web_path/PcscaleBundle/Resources/translations/*
#		ln -sf /usr/share/locale/es/LC_MESSAGES/pcscale.mo $web_path/PcscaleBundle/Resources/translations/messages.es.mo
#		ln -sf /usr/share/locale/ca/LC_MESSAGES/pcscale.mo $web_path/PcscaleBundle/Resources/translations/messages.ca.mo
#		ln -sf /usr/share/locale/fr/LC_MESSAGES/pcscale.mo $web_path/PcscaleBundle/Resources/translations/messages.fr.mo
#	fi
	sf_path="/var/www/touchscale"
	if [ -d $sf_path ]; then
		ConfigComposer
		SetSymfonyConfig
		SetSymfonyRouting
		SetSymfonySecurity
		RegisterSymfonyBundles
		ln -sf $src_path/share/pcscale/Epelsa /var/www/Symfony/src
		ln -sf /home/pcscale/scale/resources/publi $src_path/share/pcscale/Epelsa/PcscaleBundle/Resources/public
		cp -f $src_path/share/pcscale/Epelsa/PcscaleBundle/Resources/public/images/epel.ico /var/www/touchscale/web/favicon.ico
		chown www-data:www-data /var/www/touchscale/web/favicon.ico
		cd $sf_path
		
		# Turn 
		if [ $turn -eq 1 ]; then
			packages="php5-imagick"
			if [ "$nam" = "bionic" ]; then
				packages="php-imagick php-curl"
			elif [ "$nam" = "precise" ]; then
				packages="php5-imagick php5-curl"
			fi
			apt-get -qq install $packages
			if [ $? -ne 0 ]; then
				echo "Packages install failed! Test your internet connection."
				exit 1
			fi

			if [ "$nam" = "bionic" ]; then
				composer require mike42/escpos-php
				if [ $? -ne 0 ]; then
					echo "Symfony update failed! Test your internet connection."
					exit 1
				fi
			fi
		fi

		# update public resources
		app/console assets:install web
		if [ $? -ne 0 ]; then
			exit 1
		fi

		chown -R www-data:www-data /var/www/Symfony

		# remove prod cache
		rm -rf app/cache/prod
		rm -rf app/cache/dev
	else
		echo "Web server is not installed in this scale. Can't update it."
		exit 0
	fi
}

RestartServices() {
	if [ "$nam" = "precise" ]; then
		service php5-fpm restart
	fi
	if [ "$nam" = "bionic" ]; then
		service php7.2-fpm restart
	fi
	service nginx restart
	echo "Web app updated."
}

CheckPermission
WebServerUpdate
RestartServices

