#!/bin/bash

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

upgrade_type=$(ynh_check_app_version_changed)

#=================================================
# ACTIVATE MAINTENANCE MODE
#=================================================
ynh_script_progression --message="Activating maintenance mode..." --weight=2

# Wait for etherpad to be fully started # (... but why ???)
ynh_systemd_action --action=restart --line_match="You can access your Etherpad instance at" --log_path="/var/log/$app/etherpad.log" --timeout="120"

ynh_maintenance_mode_ON

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

ynh_systemd_action --service_name=$app --action="stop"

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

if [ -z "${language:-}" ]; then
    # If upgrading from a version which doesn't support translations, set language to English by default
    language=en
    ynh_app_setting_set --app=$app --key=language --value=$language
fi

if [ -z "${export:-}" ]; then
	export=none
	ynh_app_setting_set --app=$app --key=export --value=$export
fi

if [ -z "${mypads:-}" ]; then
	mypads=1
	ynh_app_setting_set --app=$app --key=mypads --value=$mypads
fi

if [ -z "${useldap:-}" ]; then
	useldap=0
	ynh_app_setting_set --app=$app --key=useldap --value=$useldap
fi

if [ -z "${path:-}" ]; then
	path="/"
	ynh_app_setting_set --app=$app --key=path --value=$path
fi

if [ -z "${password:-}" ]; then
	password=$(ynh_string_random --length=32)
	ynh_app_setting_set --app=$app --key=password --value="$password"
fi

# Support full Unicode in MySQL databases
ynh_mysql_connect_as --user=$db_user --password="$db_pwd" --database=$db_name \
    <<< "ALTER DATABASE $db_name CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;"

#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================

if [ "$upgrade_type" == "UPGRADE_APP" ]
then
	ynh_script_progression --message="Upgrading source files..." --weight=4

	# Download, check integrity, uncompress and patch the source from app.src
	ynh_setup_source --dest_dir="$install_dir" --keep="settings.json credentials.json"
fi

chmod -R o-rwx "$install_dir"
chown -R $app:$app "$install_dir"

#=================================================
# UPGRADE DEPENDENCIES
#=================================================
ynh_script_progression --message="Upgrading dependencies..." --weight=5

ynh_install_nodejs --nodejs_version=$nodejs_version
ynh_use_nodejs

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

ynh_add_nginx_config

#=================================================
# SPECIFIC UPGRADE
#=================================================
# HANDLE LOG FILES AND LOGROTATE
#=================================================
ynh_script_progression --message="Configuring log rotation..." --weight=1

# Create log directory
chown $app -R /var/log/$app

#=================================================
# CONFIGURE ETHERPAD
#=================================================

ynh_script_progression --message="Configure etherpad..."

abiword_path="null"
soffice_path="null"

if [[ "$export" == "abiword" ]]
then
    abiword_path="\"$(which abiword)\""
elif [[ "$export" == "libreoffice" ]]
then
    soffice_path="\"$(which soffice)\""
fi

# Use ldap for mypads
comment_if_ldap_disabled="//ldap_disabled"
if [ $mypads -eq 1 ] && [ $useldap -eq 1 ]
then
    comment_if_ldap_disabled=""
fi

# Calculate and store the config file checksum into the app settings

ynh_add_config --template="settings.json" --destination="$install_dir/settings.json"
ynh_add_config --template="credentials.json" --destination="$install_dir/credentials.json"

chmod 600 "$install_dir/settings.json"
chown $app:$app "$install_dir/settings.json"

chmod 600 "$install_dir/credentials.json"
chown $app:$app "$install_dir/credentials.json"

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

ynh_add_systemd_config

#=================================================
# INSTALL ETHERPAD'S PLUGINS
#=================================================
ynh_script_progression --message="Installing Etherpad plugins..." --weight=90

pushd "$install_dir"
	# Add Left/Center/Right/Justify to lines of text in a pad
	ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH $ynh_npm install --no-save ep_align@${ep_align_version}
	# Framapad - Adds author names to span titles
	ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH $ynh_npm install --no-save ep_author_hover@${ep_author_hover_version}
	# Framapad - Adds comments on sidebar and link it to the text.
	ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH $ynh_npm install --no-save ep_comments_page@${ep_comments_page_version}
	# Framapad - Displays paragraphs, sentences, words and characters counts.
	ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH $ynh_npm install --no-save ep_countable@${ep_countable_version}
	# Framapad - Delete pads which were never edited
	ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH $ynh_npm install --no-save ep_delete_empty_pads@${ep_delete_empty_pads_version}
	# Framapad - Apply colors to fonts
	ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH $ynh_npm install --no-save ep_font_color@${ep_font_color_version}
	# Framapad - Adds heading support to Etherpad Lite.
	ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH $ynh_npm install --no-save ep_headings2@${ep_headings2_version}
	# Framapad - Edit and Export as Markdown in Etherpad
	ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH $ynh_npm install --no-save ep_markdown@${ep_markdown_version}
	if [ $mypads -eq 1 ]; then
		# Framapad - Groups and private pads for Etherpad
		ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH $ynh_npm install --no-save ep_mypads@${mypads_version}
	fi
	# Framapad - Add support to do 'Spell checking'
	ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH $ynh_npm install --no-save ep_spellcheck@${ep_spellcheck_version}
	# Framapad - Add support for Subscript and Superscript
	ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH $ynh_npm install --no-save ep_subscript_and_superscript@${ep_subscript_and_superscript_version}
	# Framapad - User Pad Contents font size can be set in settings, this does not effect other peoples views
	ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH $ynh_npm install --no-save ep_font_size@${ep_font_size_version}
popd

#=================================================
# UPGRADE NPM MODULES
#=================================================
ynh_script_progression --message="Upgrading Etherpad..." --weight=10

pushd $install_dir
	ynh_exec_warn_less ynh_exec_as $app env $ynh_node_load_PATH ETHERPAD_PRODUCTION=true src/bin/installDeps.sh
popd

#=================================================
# ADD MYPADS LINK
#=================================================

if [ "$upgrade_type" == "UPGRADE_APP" ] && [ $mypads -eq 1 ]
then
	# Find the /div just after the field to open a pad in order to add a link to MyPads plugin.
	sed -i '157i<center><br><font size="4"><a href="./mypads/" style="text-decoration: none; color: #555">MyPads</a></font></center>' $install_dir/src/templates/index.html
fi

#=================================================
# GENERIC FINALIZATION
#=================================================
# SETUP LOGROTATE
#=================================================
ynh_script_progression --message="Upgrading logrotate configuration..." --weight=2

# Use logrotate to manage app-specific logfile(s)
ynh_use_logrotate --non-append --specific_user=$app/$app

#=================================================
# INTEGRATE SERVICE IN YUNOHOST
#=================================================
ynh_script_progression --message="Integrating service in YunoHost..." --weight=1

yunohost service add $app --description="Collaborative editor" --log="/var/log/$app/etherpad.log"

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

ynh_systemd_action --service_name=$app --action=restart --line_match="You can access your Etherpad instance at" --log_path="/var/log/$app/etherpad.log" --timeout="120"

#=================================================
# UPGRADE FAIL2BAN
#=================================================
ynh_script_progression --message="Reconfiguring Fail2Ban..." --weight=8

# Create a dedicated Fail2Ban config
ynh_add_fail2ban_config --logpath="/var/log/nginx/$domain-access.log" --failregex="<HOST> .* .POST /mypads/api/auth/login HTTP/1.1. 400" --max_retry=5

#=================================================
# DEACTIVE MAINTENANCE MODE
#=================================================
ynh_script_progression --message="Disabling maintenance mode..." --weight=5

ynh_maintenance_mode_OFF

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

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