#!/bin/bash

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

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

#=================================================
# MANAGE SCRIPT FAILURE
#=================================================

# Exit if an error occurs during the execution of the script
ynh_abort_if_errors

#=================================================
# RETRIEVE ARGUMENTS FROM THE MANIFEST
#=================================================

export domain=$YNH_APP_ARG_DOMAIN
export path_url=$YNH_APP_ARG_PATH
admin=$YNH_APP_ARG_ADMIN
is_public=$YNH_APP_ARG_IS_PUBLIC
language=$YNH_APP_ARG_LANGUAGE

app=$YNH_APP_INSTANCE_NAME

#=================================================
# CHECK IF THE APP CAN BE INSTALLED WITH THESE ARGS
#=================================================
ynh_script_progression --message="Validating installation parameters..."

final_path=/var/www/$app
test ! -e "$final_path" || ynh_die --message="This path already contains a folder"

# Register (book) web path
ynh_webpath_register --app=$app --domain=$domain --path_url=$path_url

#=================================================
# STORE SETTINGS FROM MANIFEST
#=================================================
ynh_script_progression --message="Storing installation settings..."

ynh_app_setting_set --app=$app --key=domain --value=$domain
ynh_app_setting_set --app=$app --key=path --value=$path_url
ynh_app_setting_set --app=$app --key=admin --value=$admin
ynh_app_setting_set --app=$app --key=is_public --value=$is_public
ynh_app_setting_set --app=$app --key=language --value=$language

#=================================================
# STANDARD MODIFICATIONS
#=================================================
# INSTALL DEPENDENCIES
#=================================================
ynh_script_progression --message="Installing dependencies..."

pid=$(pgrep -f '/usr/bin/python3 /usr/bin/unattended-upgrade --download-only' || true)
if [ ! -z "$pid" ] ;then
	ynh_script_progression --message="Check and wait end of unattended-upgrade of package_check"
	tail --pid=$pid -f /dev/null
fi

ynh_script_progression --message="Remove Zabbix if already installed"
apt-get purge zabbix* -y
if compgen -G "/var/cache/apt/archives/zabbix-server-mysql*" > /dev/null; then
	ynh_secure_remove  --file="/var/cache/apt/archives/zabbix-server-mysql*"
fi

ynh_script_progression --message="Install Zabbix repository"
install_zabbix_repo

ynh_script_progression --message="Update and install dependencies"
#ynh_package_update no need cause ynh_install_app_dependencies after
ynh_install_app_dependencies $pkg_dependencies
dpkg -i --force-confmiss /var/cache/apt/archives/zabbix-server-mysql*

ynh_replace_string --match_string="# fr_FR.UTF-8 UTF-8" --replace_string="fr_FR.UTF-8 UTF-8" --target_file=/etc/locale.gen
locale-gen

#=================================================
# CREATE A MYSQL DATABASE
#=================================================
ynh_script_progression --message="Creating a MySQL database..."

db_name=$(ynh_sanitize_dbid --db_name=$app)
db_user=$db_name
ynh_app_setting_set --app=$app --key=db_name --value=$db_name
ynh_mysql_setup_db --db_user=$db_user --db_name=$db_name

#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================
ynh_script_progression --message="Setting up source files..."

ynh_app_setting_set --app=$app --key=final_path --value=$final_path
# Download, check integrity, uncompress and patch the source from app.src
ln -s /usr/share/zabbix "$final_path"

chmod 750 "$final_path"
chmod -R o-rwx "$final_path"
chown -R $app:www-data "$final_path"

#=================================================
# NGINX CONFIGURATION
#=================================================
ynh_script_progression --message="Configuring NGINX web server..."

# Create a dedicated NGINX config
ynh_add_nginx_config

#=================================================
# PHP-FPM CONFIGURATION
#=================================================
ynh_script_progression --message="Configuring PHP-FPM..."

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

#=================================================
# SPECIFIC SETUP
#=================================================
# IMPORT DEFAULT DATA
#=================================================
ynh_script_progression --message="Import default data in database..."

export mysqlconn="mysql -u$db_user -p$db_pwd $db_name"
mysql --user=$db_user --password=$db_pwd --database=zabbix -e "ALTER DATABASE $db_name CHARACTER SET utf8 COLLATE utf8_general_ci;"

zcat /usr/share/doc/zabbix-server-mysql*/create.sql.gz | $mysqlconn

convert_ZabbixDB

#sso integration
$mysqlconn -e "UPDATE \`config\` SET \`http_auth_enabled\` = '1', \`http_login_form\` = '1' WHERE \`config\`.\`configid\` = 1;"

#admin creation
surname=$(ynh_user_get_info "$admin" lastname)
name=$(ynh_user_get_info "$admin" firstname)

$mysqlconn -e "INSERT INTO \`users\` (\`userid\`,\`alias\`, \`name\`, \`surname\`, \`passwd\`, \`url\`, \`autologin\`, \`autologout\`, \`lang\`, \`refresh\`, \`type\`, \`theme\`, \`attempt_failed\`, \`attempt_ip\`, \`attempt_clock\`, \`rows_per_page\`) VALUES (3,'$admin', '$admin', '$admin', '5fce1b3e34b520afeffb37ce08c7cd66', '', 0, '0', '$language', '30s', 3, 'default', 0, '', 0, 50);"
$mysqlconn -e "INSERT INTO \`users_groups\` (\`id\`, \`usrgrpid\`, \`userid\`) VALUES (5, 7, 3);"

#users creation in zabbix database
i=4
for user in $(ynh_user_list); 
do 
	if [ "$user" != "$admin" ];then
		surname=$(ynh_user_get_info "$user" lastname)
		name=$(ynh_user_get_info "$user" firstname)
		$mysqlconn -e "INSERT INTO \`users\` (\`userid\`, \`alias\`, \`name\`, \`surname\`, \`passwd\`, \`url\`, \`autologin\`, \`autologout\`, \`lang\`, \`refresh\`, \`type\`, \`theme\`, \`attempt_failed\`, \`attempt_ip\`, \`attempt_clock\`, \`rows_per_page\`) VALUES ($i,'$user', '$name', '$surname', '5fce1b3e34b520afeffb37ce08c7cd66', '', 0, '0', '$language', '30s', 1, 'default', 0, '', 0, 50);"
		i=$((i+1))
	fi
done

disable_guest_user

set_mediatype_default_yunohost

#=================================================
# ADD A CONFIGURATION
#=================================================
ynh_script_progression --message="Adding a configuration file..."

ynh_add_config --template="../conf/zabbix.conf.php" --destination="/usr/share/zabbix/conf/zabbix.conf.php"

chown -R www-data. /usr/share/zabbix

ynh_replace_string --match_string="DBName=zabbix" --replace_string="DBName=$db_name" --target_file=/etc/zabbix/zabbix_server.conf
ynh_replace_string --match_string="DBUser=zabbix" --replace_string="DBUser=$db_user" --target_file=/etc/zabbix/zabbix_server.conf
ynh_replace_string --match_string="# DBPassword=" --replace_string="# DBPassword=\nDBPassword=$db_pwd" --target_file=/etc/zabbix/zabbix_server.conf

#=================================================
# INSTALL hook to verify if conf file is broken (after an update for example)
#=================================================

update_initZabbixConf

#=================================================
# IMPORT YUNOHOST TEMPLATE
#=================================================
ynh_script_progression --message="Importing YunoHost template in Zabbix"

import_template

#=================================================
# 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"
yunohost service add zabbix-agent --description="Management Zabbix agent daemon : send informations about this host to the server"

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

systemctl enable zabbix-agent --quiet && systemctl restart zabbix-agent
change_timeoutAgent
systemctl enable zabbix-server --quiet && systemctl restart zabbix-server

#test if zabbix server is started
check_proc_zabbixagent

#test if zabbix agent is started
check_proc_zabbixserver

#=================================================
# 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="Installation of $app completed"
