#!/bin/bash

#=================================================
# GENERIC STARTING
#=================================================
# IMPORT GENERIC HELPERS
#=================================================

# Load common variables for all scripts.
source _variables
source _common.sh
source /usr/share/yunohost/helpers

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

app=$YNH_APP_INSTANCE_NAME

domain=$(ynh_app_setting_get --app=$app --key=domain)
path_url=$(ynh_app_setting_get --app=$app --key=path)
admin=$(ynh_app_setting_get --app=$app --key=admin)
language=$(ynh_app_setting_get --app=$app --key=language)
final_path=$(ynh_app_setting_get --app=$app --key=final_path)
port=$(ynh_app_setting_get --app=$app --key=port)
export=$(ynh_app_setting_get --app=$app --key=export)
db_name=$(ynh_app_setting_get --app=$app --key=db_name)
db_user=$db_name
db_pwd=$(ynh_app_setting_get --app=$app --key=mysqlpwd)
ynh_print_OFF; password=$(ynh_app_setting_get --app=$app --key=password); ynh_print_ON
mypads=$(ynh_app_setting_get --app=$app --key=mypads)
useldap=$(ynh_app_setting_get --app=$app --key=useldap)
overwrite_settings=$(ynh_app_setting_get --app=$app --key=overwrite_settings)
overwrite_credentials=$(ynh_app_setting_get --app=$app --key=overwrite_credentials)
overwrite_nginx=$(ynh_app_setting_get --app=$app --key=overwrite_nginx)
overwrite_systemd=$(ynh_app_setting_get --app=$app --key=overwrite_systemd)

# Optional parameters from config-panel feature
pad_config_nocolors=$(ynh_app_setting_get --app=$app --key=pad_config_nocolors)
pad_config_showlinenumbers=$(ynh_app_setting_get --app=$app --key=pad_config_showlinenumbers)
pad_config_chatandusers=$(ynh_app_setting_get --app=$app --key=pad_config_chatandusers)
pad_config_alwaysshowchat=$(ynh_app_setting_get --app=$app --key=pad_config_alwaysshowchat)
pad_config_show_markdown=$(ynh_app_setting_get --app=$app --key=pad_config_show_markdown)

#=================================================
# CHECK VERSION
#=================================================

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

upgrade_type=$(ynh_check_app_version_changed)

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

# 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 abiword setting doesn't exist
if [ -z "$abiword" ]; then
	abiword=0
	ynh_app_setting_set --app=$app --key=abiword --value=$abiword
fi

# If abiword setting exists
if [ -n "$abiword" ]; then
	if [ $abiword -eq 1 ]; then
		export=abiword
	fi
	ynh_app_setting_set --app=$app --key=export --value=$export
	ynh_app_setting_delete --app=$app --key=abiword
fi

# If export setting doesn't exist
if [ -z "$export" ]; then
	export=none
	ynh_app_setting_set --app=$app --key=export --value=$export
fi

# If mypads setting doesn't exist
if [ -z "$mypads" ]; then
	mypads=1
	ynh_app_setting_set --app=$app --key=mypads --value=$mypads
fi

# If useldap setting doesn't exist
if [ -z "$useldap" ]; then
	useldap=0
	ynh_app_setting_set --app=$app --key=useldap --value=$useldap
fi

# If path_url setting doesn't exist
if [ -z "$path_url" ]; then
	path_url="/"
	ynh_app_setting_set --app=$app --key=path --value=$path_url
fi

# If overwrite_settings doesn't exist, create it
if [ -z "$overwrite_settings" ]; then
	overwrite_settings=1
	ynh_app_setting_set $app overwrite_settings $overwrite_settings
fi

# If overwrite_credentials doesn't exist, create it
if [ -z "$overwrite_credentials" ]; then
	overwrite_credentials=1
	ynh_app_setting_set $app overwrite_credentials $overwrite_credentials
fi

# If overwrite_nginx doesn't exist, create it
if [ -z "$overwrite_nginx" ]; then
	overwrite_nginx=1
	ynh_app_setting_set $app overwrite_nginx $overwrite_nginx
fi

# If overwrite_systemd doesn't exist, create it
if [ -z "$overwrite_systemd" ]; then
	overwrite_systemd=1
	ynh_app_setting_set $app overwrite_systemd $overwrite_systemd
fi

# Cleaning legacy permissions
if ynh_legacy_permissions_exists; then
  ynh_legacy_permissions_delete_all

  ynh_app_setting_delete --app=$app --key=is_public
fi

if ! ynh_permission_exists --permission="admin"; then
  # Create the required permissions
  ynh_permission_create --permission="admin" --url="/admin" --allowed=$admin
  if [ $mypads -eq 1 ]; then
    ynh_permission_create --permission="mypads_admin" --url="/mypads/?/admin" --allowed=$admin
  fi
fi

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

# Backup the current version of the app
ynh_backup_before_upgrade
ynh_clean_setup () {
# Clean installation remainings that are not handled by the remove script.
	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

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

ynh_maintenance_mode_ON

#=================================================
# STOP ETHERPAD
#=================================================
ynh_script_progression --message="Stopping Etherpad service..." --weight=3

ynh_systemd_action --action=stop

#=================================================
# CREATE DEDICATED USER
#=================================================
ynh_script_progression --message="Making sure dedicated system user exists..."

# Create a dedicated user (if not existing)
ynh_system_user_create --username=$app --home_dir=$final_path

#=================================================
# STANDARD UPGRADE STEPS
#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================

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

  # # Create a temporary directory
  # tmpdir="$(mktemp -d)"
  # # Backup the config file in the temp dir
  # cp -a "$final_path/settings.json" "$tmpdir/settings.json"

  ynh_secure_remove --file="$final_path"

	# Download, check integrity, uncompress and patch the source from app.src
	ynh_setup_source --dest_dir="$final_path"

  #   # Copy the admin saved settings from tmp directory to final config path 
  # cp -a "$tmpdir/settings.json" "$final_path/settings.json" 

  # # Remove the tmp directory securely
  # ynh_secure_remove --file="$tmpdir"

fi

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

if [ "$export" = "abiword" ]; then
	ynh_exec_warn_less ynh_install_app_dependencies $abiword_app_depencencies
elif [ "$export" = "libreoffice" ]; then
	ynh_exec_warn_less ynh_install_app_dependencies $libreoffice_app_dependencies
fi

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

# Overwrite the NGINX configuration only if it's allowed
if [ $overwrite_nginx -eq 1 ]
then
	ynh_add_nginx_config
fi

#=================================================
# UPGRADE NODEJS
#=================================================
ynh_script_progression --message="Upgrading NodeJS..." --weight=4

ynh_install_nodejs --nodejs_version=$nodejs_version

#=================================================
# HANDLE LOG FILES AND LOGROTATE
#=================================================
ynh_script_progression --message="Configuring log rotation..."

# Create log directory
install_log=/var/log/$app/installation.log
touch $install_log
chown $app -R /var/log/$app

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

# Then update the additionnal modules
chown -R $app: $final_path

pushd $final_path
  ynh_use_nodejs
  ynh_exec_as $app env "$ynh_node_load_PATH" src/bin/installDeps.sh
# ynh_exec_warn_less npm cache clean --force
# ynh_exec_warn_less ynh_exec_as $app env "$ynh_node_load_PATH" npm cache clean --force
# while read node_module
# do
#     # Ignore ep_etherpad-lite, this part is updated before in this script.
#     if [ "$node_module" = "ep_etherpad-lite" ]; then
#         continue
#     fi
#     echo "Update $node_module"
#     # Build the name of the variable with the version.
#     module_version=${node_module}_version
#     # Get the content of the variable (from the file _variables)
#     module_version=${!module_version:-}
#     # If the module has no version stored in a variable into the file, keep it empty.
#     # That way, the upgrade will not be specific to a version.
#     ## Otherwise, add @ before the version number to force the upgrade to this version.
#     if [ -n "${module_version}" ]; then
#         module_version=@${module_version}
#     fi
#     ynh_exec_warn_less ynh_exec_as $app env "$ynh_node_load_PATH" npm install --upgrade ${node_module}${module_version} || true
# done <<< "$(ls -1 "$final_path/node_modules" | grep "^ep_")"
popd

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

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

#=================================================
# SPECIFIC UPGRADE
#=================================================
# CONFIGURE ETHERPAD
#=================================================

if [ "$upgrade_type" == "UPGRADE_APP" ]
then
	ynh_script_progression --message="Reconfiguring Etherpad..." --weight=3

  # Overwrite the settings config file only if it's allowed
  if [ $overwrite_settings -eq 1 ]
  then
    # Verify the checksum of a file, stored by `ynh_store_file_checksum` in the install script.
    ynh_backup_if_checksum_is_different --file="$final_path/settings.json"
    cp ../conf/settings.json "$final_path/settings.json"
    ynh_replace_string --match_string="__PORT__" --replace_string="$port" --target_file="$final_path/settings.json"

    if [ "$export" = "abiword" ]
    then
      # Get abiword binary path
      abiword_path=`which abiword`
      # Set the path of Abiword into Etherpad config
      ynh_replace_string --match_string="\"abiword\" : null" --replace_string="\"abiword\" : \"$abiword_path\"" --target_file="$final_path/settings.json"
    elif [ "$export" = "libreoffice" ]
    then
      # Get soffice binary path
      soffice_path=`which soffice`
      # Set the path of soffice into Etherpad config
      ynh_replace_string --match_string="\"soffice\" : null" --replace_string="\"soffice\" : \"$soffice_path\"" --target_file="$final_path/settings.json"
    fi

    if test -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
    ynh_replace_string --match_string="__LANGUAGE__" --replace_string="$language" --target_file="$final_path/settings.json"

    # Use LDAP for MyPads
    if [ $mypads -eq 1 ] && [ $useldap -eq 1 ]
    then
      ynh_replace_string --match_string="//noldap" --replace_string="" --target_file="$final_path/settings.json"
    fi

    # Optional parameters from config-panel feature
    if [ -n "$pad_config_nocolors" ]; then
      ynh_replace_string --match_string="\(\"noColors\" *: \).*," --replace_string="\1$pad_config_nocolors," --target_file="$final_path/settings.json"
    fi
    if [ -n "$pad_config_showlinenumbers" ]; then
      ynh_replace_string --match_string="\(\"showLineNumbers\" *: \).*," --replace_string="\1$pad_config_showlinenumbers," --target_file="$final_path/settings.json"
    fi
    if [ -n "$pad_config_chatandusers" ]; then
      ynh_replace_string --match_string="\(\"chatAndUsers\" *: \).*," --replace_string="\1$pad_config_chatandusers," --target_file="$final_path/settings.json"
    fi
    if [ -n "$pad_config_alwaysshowchat" ]; then
      ynh_replace_string --match_string="\(\"alwaysShowChat\" *: \).*," --replace_string="\1$pad_config_alwaysshowchat," --target_file="$final_path/settings.json"
    fi
    if [ -n "$pad_config_show_markdown" ]; then
      ynh_replace_string --match_string="\(\"ep_markdown_default\" *: \).*," --replace_string="\1$pad_config_show_markdown," --target_file="$final_path/settings.json"
    fi

    # Recalculate and store the checksum of the file for the next upgrade.
    ynh_store_file_checksum --file="$final_path/settings.json"
  fi

  # Overwrite the credentials config file only if it's allowed
  if [ $overwrite_credentials -eq 1 ]
  then
    ynh_add_config --template="../conf/credentials.json" --destination="$final_path/credentials.json"
  fi
fi

#=================================================
# SECURING FILES AND DIRECTORIES
#=================================================

# Set files ownership to Etherpad
chown -R $app: $final_path
chmod o-rwx $final_path
# Restrict access to credentials.json
chmod 600 "$final_path/credentials.json"
chown $app -R /var/log/$app/etherpad.log

#=================================================
# ADVERTISE SERVICE IN ADMIN PANEL
#=================================================

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

#=================================================
# 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

#=================================================
# SETUP LOGROTATE
#=================================================
ynh_script_progression --message="Upgrading logrotate configuration..."

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

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

# Overwrite the systemd configuration only if it's allowed
if [ $overwrite_systemd -eq 1 ]
then
	ynh_add_systemd_config --others_var="ynh_node_load_PATH"
fi

#=================================================
# SOME HACKS
#=================================================

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>' $final_path/src/templates/index.html
fi

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

ynh_systemd_action --action=reload --service_name=nginx

#=================================================
# CHECK ETHERPAD STARTING
#=================================================
ynh_script_progression --message="Restarting Etherpad..." --weight=9

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

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

ynh_maintenance_mode_OFF

#=================================================
# SEND A README FOR THE ADMIN
#=================================================

# Get main domain and buid the URL of the admin panel of the app.
admin_panel="https://$(grep portal_domain /etc/ssowat/conf.json | cut -d'"' -f4)/yunohost/admin/#/apps/$app"

# Build the changelog
# Get the value of admin_mail_html
admin_mail_html=$(ynh_app_setting_get $app admin_mail_html)
admin_mail_html="${admin_mail_html:-0}"
# If a html email is required. Apply html to the changelog.
if [ "$admin_mail_html" -eq 1 ]; then
    format=html
else
    format=plain
fi
ynh_app_changelog --format=$format

if [ $mypads -eq 1 ]
then
	Informations="You can access 2 different admin panels, for Etherpad by accessing https://$domain${path_url%/}/admin and for MyPads by accessing https://$domain${path_url%/}/mypads/?/admin."
else
	Informations="You can access the admin panel by accessing https://$domain${path_url%/}/admin."
fi

echo "$Informations
You can also find a config file for Etherpad at this path /var/www/etherpad_mypads/settings.json.

You can configure this app easily by using the experimental config-panel feature $admin_panel/config-panel.
You can also find some specific actions for this app by using the experimental action feature $admin_panel/actions.

If you are facing an issue or want to improve this app, please open a new issue in this project: https://github.com/YunoHost-Apps/etherpad_mypads_ynh

---

Changelog since your last upgrade:
$(cat changelog)" > mail_to_send

ynh_send_readme_to_admin --app_message="mail_to_send" --recipients="$admin" --type=upgrade

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

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