#!/bin/bash

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

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

#=================================================
# MANAGE FAILURE OF THE SCRIPT
#=================================================

ynh_clean_setup () {
# Nettoyage des résidus d'installation non pris en charge par le script remove.
	ynh_clean_check_starting
}
ynh_abort_if_errors	# Active trap pour arrêter le script si une erreur est détectée.

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

domain=$YNH_APP_ARG_DOMAIN
path_url=$YNH_APP_ARG_PATH
admin=$YNH_APP_ARG_ADMIN
ynh_print_OFF; password=$YNH_APP_ARG_PASSWORD; ynh_print_ON
language=$YNH_APP_ARG_LANGUAGE
is_public=$YNH_APP_ARG_IS_PUBLIC
export=$YNH_APP_ARG_EXPORT
mypads=$YNH_APP_ARG_MYPADS
useldap=$YNH_APP_ARG_USELDAP

app=$YNH_APP_INSTANCE_NAME

#=================================================
# CHECK IF THE APP CAN BE INSTALLED WITH THIS ARGS
#=================================================

ynh_print_OFF
if [ "${#password}" -lt 8 ] || [ "${#password}" -gt 30 ]
then
	ynh_die "The password must have between 8 and 30 characters."
fi
ynh_print_ON

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

# Normalize the url path syntax
path_url=$(ynh_normalize_url_path $path_url)

# Check web path availability
ynh_webpath_available $domain $path_url
# Register (book) web path
ynh_webpath_register $app $domain $path_url

#=================================================
# STORE SETTINGS FROM MANIFEST
#=================================================

ynh_app_setting_set $app domain $domain
ynh_app_setting_set $app path $path_url
ynh_app_setting_set $app admin $admin
ynh_app_setting_set $app is_public $is_public
ynh_print_OFF; ynh_app_setting_set $app password $password; ynh_print_ON
ynh_app_setting_set $app language $language
ynh_app_setting_set $app export $export
ynh_app_setting_set $app mypads $mypads
ynh_app_setting_set $app useldap $useldap
ynh_app_setting_set $app overwrite_settings "1"
ynh_app_setting_set $app overwrite_credentials "1"
ynh_app_setting_set $app overwrite_nginx "1"
ynh_app_setting_set $app overwrite_systemd "1"

#=================================================
# ACTIVATE MAINTENANCE MODE
#=================================================

ynh_maintenance_mode_ON

#=================================================
# STANDARD MODIFICATIONS
#=================================================
# FIND AND OPEN A PORT
#=================================================

port=$(ynh_find_port 9001)	# Look for an available port
ynh_app_setting_set $app port $port

#=================================================
# INSTALL DEPENDENCIES
#=================================================

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

#=================================================
# INSTALL NODEJS
#=================================================

ynh_install_nodejs $nodejs_version

#=================================================
# CREATE A SQL DB
#=================================================

db_name=$(ynh_sanitize_dbid $app)
ynh_app_setting_set $app db_name $db_name
ynh_mysql_setup_db $db_name $db_name

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

ynh_app_setting_set $app final_path $final_path
ynh_setup_source "$final_path"	# Download, check integrity and uncompress the source from app.src

#=================================================
# NGINX CONFIGURATION
#=================================================

if [ "$path_url" != "/" ]
then
	ynh_replace_string "^#sub_path_only" "" "../conf/nginx.conf"
fi
ynh_replace_string "__PATH__/" "${path_url%/}/" "../conf/nginx.conf"
ynh_add_nginx_config

#=================================================
# CREATE DEDICATED USER
#=================================================

ynh_system_user_create $app $final_path	# Create a dedicated system user

#=================================================
# SPECIFIC SETUP
#=================================================
# HANDLE LOG FILES AND LOGROTATE
#=================================================

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

# Setup logrotate
ynh_use_logrotate

#=================================================
# INSTALL ETHERPAD
#=================================================

# Install dependencies and proceed with the installation
ynh_use_nodejs
"$final_path/bin/installDeps.sh" > $install_log 2>&1
npm install forever -g >> $install_log 2>&1

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

cp ../conf/settings.json "$final_path/settings.json"
cp ../conf/credentials.json "$final_path/credentials.json"
ynh_replace_string "__PORT__" "$port" "$final_path/settings.json"
ynh_replace_string "__DB_USER__" "$db_name" "$final_path/credentials.json"
ynh_replace_string "__DB_PWD__" "$db_pwd" "$final_path/credentials.json"
ynh_replace_string "__ADMIN__" "$admin" "$final_path/credentials.json"
ynh_print_OFF; ynh_replace_special_string "__PASSWD__" "$password" "$final_path/credentials.json"; ynh_print_ON
if [ "$export" = "abiword" ]
then
	abiword_path=`which abiword`	# Get abiword binary path
	ynh_replace_string "\"abiword\" : null" "\"abiword\" : \"$abiword_path\"" "$final_path/settings.json"	# Renseigne l'emplacement de abiword dans la config de etherpad
elif [ "$export" = "libreoffice" ]
then
	soffice_path=`which soffice`	# Get soffice binary path
	ynh_replace_string "\"soffice\" : null" "\"soffice\" : \"$soffice_path\"" "$final_path/settings.json"	# Renseigne l'emplacement de abiword dans la config de etherpad
fi
ynh_replace_string "__LANGUAGE__" "$language" "$final_path/settings.json"

# Use ldap for mypads
if [ $mypads -eq 1 ] && [ $useldap -eq 1 ]
then
	ynh_replace_string "//noldap\(.*\)" "\1 //useldap" "$final_path/settings.json"
fi

ynh_store_file_checksum "$final_path/settings.json"	#  Store config file checksum
ynh_store_file_checksum "$final_path/credentials.json"	# Store config file checksum

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

# Set files ownership to etherpad
chown -R $app: $final_path
chmod 600 $final_path/credentials.json	# Restrict access to credentials.json

#=================================================
# SETUP SYSTEMD
#=================================================

ynh_replace_string "__ENV_PATH__" "$PATH" "../conf/systemd.service"
ynh_add_systemd_config

#=================================================
# ENABLE SERVICE IN ADMIN PANEL
#=================================================

# Add service to YunoHost monitoring panel
yunohost service add $app --log "/var/log/$app/etherpad.log"

#=================================================
# INSTALL FRAMAPAD'S PLUGINS
#=================================================

pushd "$final_path"
npm install ep_align	# Add Left/Center/Right/Justify to lines of text in a pad
npm install ep_author_hover >> $install_log 2>&1	# Framapad - Adds author names to span titles
npm install ep_automatic_logut >> $install_log 2>&1	# Automatically disconnects user after some period of time (Prevent server overload)
npm install ep_comments_page >> $install_log 2>&1	# Framapad - Adds comments on sidebar and link it to the text.
npm install ep_countable >> $install_log 2>&1	# Framapad - Displays paragraphs, sentences, words and characters counts.
npm install ep_delete_empty_pads >> $install_log 2>&1	# Framapad - Delete pads which were never edited
npm install ep_font_color >> $install_log 2>&1	# Framapad - Apply colors to fonts
npm install ep_headings2 >> $install_log 2>&1	# Framapad - Adds heading support to Etherpad Lite.
npm install ep_markdown >> $install_log 2>&1	# Framapad - Edit and Export as Markdown in Etherpad
if [ $mypads -eq 1 ]; then
	npm install ep_mypads@${mypads_version} >> $install_log 2>&1	# Framapad - Groups and private pads for etherpad
fi
npm install ep_page_view >> $install_log 2>&1	# Framapad - Add support to do 'page view', with a toggle on/off option in Settings, also Page Breaks with Control Enter
npm install ep_spellcheck >> $install_log 2>&1	# Framapad - Add support to do 'Spell checking'
npm install ep_subscript_and_superscript >> $install_log 2>&1	# Framapad - Add support for Subscript and Superscript
npm install ep_table_of_contents >> $install_log 2>&1	# Framapad - View a table of contents for your pad
npm install ep_user_font_size >> $install_log 2>&1	# Framapad - User Pad Contents font size can be set in settings, this does not effect other peoples views
popd
chown -R $app: $final_path/node_modules

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

if [ $mypads -eq 1 ]
then
	# Add a link to etherpad to allow anonymous pads creation from Mypads.
	ynh_replace_string "^ *\"DESCRIPTION\": .*</ul>" "&<a href=../>Pads anonymes</a>" $final_path/node_modules/ep_mypads/static/l10n/fr.json
	ynh_replace_string "^ *\"DESCRIPTION\": .*</ul>" "&<a href=../>Anonymous pads</a>" $final_path/node_modules/ep_mypads/static/l10n/en.json
	# And a link to etherpad admin from Mypads.
	ynh_replace_string "^ *\"FOOTER\": .*2.0" "& | <a href='../admin'>Etherpad admin</a>" $final_path/node_modules/ep_mypads/static/l10n/en.json
	ynh_replace_string "^ *\"FOOTER\": .*2.0" "& | <a href='../admin'>Etherpad admin</a>" $final_path/node_modules/ep_mypads/static/l10n/fr.json

	mod_line=$(grep -nA5 "index.createOpenPad" $final_path/src/templates/index.html | grep "</div>" | cut -d '-' -f 1)	# Recherche le /div situé sous le champs d'ouverture de pad.
	sed -i "$mod_line s@div>@&\n\t<center><br><font size="5"><a href="./mypads/">Mypads</a></font></center>@" $final_path/src/templates/index.html	# Pour ajouter un lien vers le plugin mypads depuis la page d'Etherpad.
fi

#=================================================
# SETUP FAIL2BAN
#=================================================

ynh_add_fail2ban_config "/var/log/nginx/$domain-access.log" "<HOST> .* \"POST /mypads/api/auth/login HTTP/1.1\" 400" 5

#=================================================
# SETUP SSOWAT
#=================================================

if [ $is_public -eq 1 ]; then
	ynh_app_setting_set $app skipped_uris "/"
else
	ynh_app_setting_set $app skipped_uris "/admin"	# etherpad admin page doesn't support SSO...
fi

#=================================================
# RELOAD NGINX
#=================================================

ynh_system_reload nginx

#=================================================
# CHECK ETHERPAD STARTING
#=================================================

# Wait for etherpad to be fully started
ynh_check_starting "You can access your Etherpad instance at" "/var/log/$app/etherpad.log" "120"

if [ $mypads -eq 1 ]
then
	ynh_replace_string "__LANGUAGE__" "$language" "../conf/lang_mypads.sql"
	mysql -u $db_name -p$db_pwd $db_name < "../conf/lang_mypads.sql"

	# Wait for etherpad to be fully started
	ynh_check_starting "You can access your Etherpad instance at" "/var/log/$app/etherpad.log" "120"
fi

#=================================================
# DEACTIVE MAINTENANCE MODE
#=================================================

ynh_maintenance_mode_OFF

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

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

ynh_print_OFF
message="$Informations
Or, you can find a config file for etherpad at this path /var/www/etherpad_mypads/settings.json.

Your credentials for the admin panel are:
- login		: $admin
- password	: $password

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"

ynh_send_readme_to_admin "$message" "$admin"
ynh_print_ON