#!/bin/bash

#=================================================
# GENERIC START
#=================================================
# IMPORT GENERIC HELPERS
#=================================================

source _common.sh
source /usr/share/yunohost/helpers

#=================================================
# LOAD SETTINGS
#=================================================
ynh_script_progression --message="Loading installation settings..."

app=$YNH_APP_INSTANCE_NAME

domain=$(ynh_app_setting_get --app=$app --key=domain)
path_url=$(ynh_app_setting_get --app=$app --key=path)
final_path=$(ynh_app_setting_get --app=$app --key=final_path)
db_name=$(ynh_app_setting_get --app=$app --key=db_name)
db_user=$(ynh_app_setting_get --app=$app --key=db_user)
db_pwd=$(ynh_app_setting_get --app=$app --key=mysqlpwd)
language=$(ynh_app_setting_get --app=$app --key=language)

trustedversion="4.4-1+stretch"
if ynh_permission_has_user --permission=main --user=visitors
then
	is_public=0
else
	is_public=1
fi

#=================================================
# CHECK VERSION
#=================================================
ynh_script_progression --message="Checking version..."

upgrade_type=$(ynh_check_app_version_changed)

#=================================================
# BACKUP BEFORE UPGRADE THEN ACTIVE TRAP
#=================================================
ynh_script_progression --message="Backing up the app before upgrading (may take a while)..."

# Backup the current version of the app
ynh_backup_before_upgrade
ynh_clean_setup () {
	ynh_clean_check_starting
	# Restore it if the upgrade fails
	ynh_restore_upgradebackup
}
# Exit if an error occurs during the execution of the script
ynh_abort_if_errors

#=================================================
# STANDARD UPGRADE STEPS
#=================================================
# STOP SYSTEMD SERVICE
#=================================================
ynh_script_progression --message="Stopping a systemd service..."

ynh_systemd_action --service_name=$app-server --action="stop" --log_path="/var/log/$app/${app}_server.log"
ynh_systemd_action --service_name=$app-agent --action="stop" --log_path="/var/log/$app/${app}_agent.log"

#=================================================
# ENSURE DOWNWARD COMPATIBILITY
#=================================================
ynh_script_progression --message="Ensuring downward compatibility..."

# If db_name doesn't exist, create it
if [ -z "$db_name" ]; then
	db_name=$(ynh_sanitize_dbid --db_name=$app)
	ynh_app_setting_set --app=$app --key=db_name --value=$db_name
fi

# If final_path doesn't exist, create it
if [ -z "$final_path" ]; then
	final_path=/var/www/$app
	ynh_app_setting_set --app=$app --key=final_path --value=$final_path
fi

if [ "$language" == "fr" ]
then
	language="fr_FR"
	ynh_app_setting_set --app=$app --key=language --value=$language
fi

if [ "$language" == "en" ]
then
	language="en_GB"
	ynh_app_setting_set --app=$app --key=language --value=$language
fi

export mysqlconn="mysql --user=$db_user --password=$db_pwd --database=$db_name"

# patch if zabbix-release installed
if [ "$(dpkg -l zabbix-release 2>/dev/null | wc -l)" -ne 0 ]
then
	DEBIAN_FRONTEND=noninteractive apt purge zabbix-release -y
	install_zabbix_repo
fi

# patch if zabbix-release has Candidate version but no Installed version
if [ -f "/etc/apt/sources.list.d/zabbix.list" ]
then
	if [ "$(grep -c "4.2" /etc/apt/sources.list.d/zabbix.list)" -eq 1 ]
	then
		install_zabbix_repo
		upgrade_type="UPGRADE_APP"
	fi
fi

# patch to remove old zabbix-client service
if [ ! -z "$(yunohost service status | grep zabbix-client)" ]
then 
	ynh_script_progression --message="remove zabbix-client old service"
	yunohost service remove zabbix-client
fi

ynh_remove_logrotate

# Check if new zabbix version is available on repo"

ynh_package_update
zabbixReleaseInstalledVersion=$(apt-cache policy zabbix-release | sed -n '2p' | grep -Po ".* \K(.*)")

if [[ "$trustedversion" > "$zabbixReleaseInstalledVersion" ]]
then
	upgrade_type="UPGRADE_APP"
fi

if [ -f "/etc/zabbix/web/zabbix.conf.php" ]
then
	ynh_secure_remove --file="/etc/zabbix/web/zabbix.conf.php"
fi

ynh_add_config --template="../conf/etc_zabbix_web_zabbix.conf.php" --destination="/etc/zabbix/web/zabbix.conf.php"

chmod 400 "/etc/zabbix/web/zabbix.conf.php"
chown $app:www-data "/etc/zabbix/web/zabbix.conf.php"

if [ -f "/usr/share/zabbix/conf/zabbix.conf.php" ]
then
	ynh_secure_remove --file="/usr/share/zabbix/conf/zabbix.conf.php"
fi

ln -s "/etc/zabbix/web/zabbix.conf.php" "/usr/share/zabbix/conf/zabbix.conf.php"

#=================================================
# NGINX CONFIGURATION
#=================================================
ynh_script_progression --message="Upgrading NGINX web server configuration..."

# Create a dedicated NGINX config
ynh_add_nginx_config

#=================================================
# UPGRADE DEPENDENCIES
#=================================================

if [ "$upgrade_type" == "UPGRADE_APP" ]
then
	ynh_script_progression --message="Upgrading dependencies..."

	DEBIAN_FRONTEND=noninteractive apt-mark unhold zabbix-server-mysql zabbix-frontend-php
	ynh_exec_warn_less ynh_install_app_dependencies $pkg_dependencies
fi

#=================================================
# RESTORE THE APP MAIN DIR
#=================================================
ynh_script_progression --message="Restoring the app main directory..."

chmod 750 "/usr/share/zabbix"
chmod -R o-rwx "/usr/share/zabbix"
chown -R $app:www-data "/usr/share/zabbix"

#=================================================
# PHP-FPM CONFIGURATION
#=================================================
ynh_script_progression --message="Upgrading PHP-FPM configuration..."

# Create a dedicated PHP-FPM config
ynh_add_fpm_config --package="$extra_php_dependencies"
phpversion=$(ynh_app_setting_get --app=$app --key=phpversion)

#=================================================
# SPECIFIC UPGRADE
#=================================================
# CUSTOMIZE DATABASE
#=================================================
ynh_script_progression --message="Customize the database..."

convert_ZabbixDB

set_mediatype_default_yunohost

#=================================================
# SETUP APPLICATION WITH CURL
#=================================================
ynh_script_progression --message="Setuping application with CURL..."

# Set the app as temporarily public for curl call
ynh_script_progression --message="Configuring SSOwat..."
# Making the app public for curl
if [ $is_public -eq 0 ]
then
	ynh_permission_update --permission="main" --add="visitors"
fi

enable_admin_user

import_template

link_template

disable_admin_user

disable_guest_user

# Remove the public access
ynh_permission_update --permission="main" --remove="visitors"

#=================================================
# SETUP SYSTEMD
#=================================================
ynh_script_progression --message="Upgrading systemd configuration..."

change_timeoutAgent

systemctl enable zabbix-agent --quiet
systemctl enable zabbix-server --quiet

update_initZabbixConf

#=================================================
# GENERIC FINALIZATION
#=================================================
# INTEGRATE SERVICE IN YUNOHOST
#=================================================
ynh_script_progression --message="Integrating service in YunoHost..."

yunohost service add snmpd --description="Management of SNMP Daemon"
yunohost service add zabbix-server --description="Management Zabbix server daemon : collect, agregate, compute and notify" --log="/var/log/$app/${app}_server.log"
yunohost service add zabbix-agent --description="Management Zabbix agent daemon : send informations about this host to the server" --log="/var/log/$app/${app}_agent.log"

#=================================================
# START SYSTEMD SERVICE
#=================================================
ynh_script_progression --message="Starting a systemd service..."

# Start a systemd service
ynh_systemd_action --service_name=$app-server --action="restart" --log_path="/var/log/$app/${app}_server.log"
ynh_systemd_action --service_name=$app-agent --action="restart" --log_path="/var/log/$app/${app}_agent.log"

#=================================================
# SETUP SSOWAT
#=================================================
ynh_script_progression --message="Configuring permissions..."

# Make app public if necessary
if [ $is_public -eq 1 ]
then
	# Everyone can access the app.
	# The "main" permission is automatically created before the install script.
	ynh_permission_update --permission="main" --add="visitors"
fi

#=================================================
# RELOAD NGINX
#=================================================
ynh_script_progression --message="Reloading NGINX web server..."

ynh_systemd_action --service_name=nginx --action=reload

#=================================================
# END OF SCRIPT
#=================================================

ynh_script_progression --message="Upgrade of $app completed"
