#!/bin/bash

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

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

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

ynh_clean_setup () {
# Nettoyage des résidus d'installation non pris en charge par le script remove.
	if test -n "$PID_TAIL"
	then
		SUPPRESS_WARNING kill -s 15 $PID_TAIL	# Arrête l'exécution de tail.
		ynh_secure_remove "$tempfile"
	fi
	echo ""
}
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
admin=$YNH_APP_ARG_ADMIN
password=$YNH_APP_ARG_PASSWORD
language=$YNH_APP_ARG_LANGUAGE
is_public=$YNH_APP_ARG_IS_PUBLIC
abiword=$YNH_APP_ARG_ABIWORD
path_url="" # Assure la compatibilité avec les fonctions utilisant $path_url

app=$YNH_APP_INSTANCE_NAME

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

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

if sudo yunohost domain list | grep -q $domain	# Vérifie la liste des domaines
then	# Si le domaine existe dans Yunohost
	if sudo yunohost app map | grep -q $domain	# Vérifie la liste des apps par domaine
	then 	# Si une app est installée sur ce domaine.
		WARNING echo "An app is already installed on the domain $domain. Mypads needs a whole domain or subdomain to himself."
	fi
fi

CHECK_DOMAINPATH	# Vérifie la disponibilité du path et du domaine.
CHECK_FINALPATH	# Vérifie que le dossier de destination n'est pas déjà utilisé.

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

ynh_app_setting_set $app domain $domain
ynh_app_setting_set $app admin $admin
ynh_app_setting_set $app is_public $is_public
ynh_app_setting_set $app password $password
ynh_app_setting_set $app language $language
ynh_app_setting_set $app abiword $abiword

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

port=$(ynh_find_port 9001)	# Cherche un port libre.
ynh_app_setting_set $app port $port

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

if [ $abiword -eq 1 ]
then
	ynh_install_app_dependencies abiword
fi

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

ynh_install_nodejs 0.10

#=================================================
# CREATE A SQL BDD
#=================================================

db_name=$(ynh_make_valid_dbid $app)
ynh_app_setting_set $app db_name $db_name
ynh_mysql_generate_db $db_name $db_name

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

ynh_app_setting_set $app final_path $final_path
ynh_setup_source	# Télécharge la source, décompresse et copie dans $final_path

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

ynh_nginx_config

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

ynh_system_user_create $app	# Créer un utilisateur système dédié à l'app

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

# Créer le dossier de log
sudo mkdir -p /var/log/$app
sudo touch /var/log/$app/etherpad.log
install_log=/var/log/$app/installation.log
sudo touch $install_log
sudo chown $app -R /var/log/$app
sudo chown admin -R $install_log

# Configuration de logrotate
ynh_use_logrotate

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

# final_path doit appartenir à `admin` pour l'exécution de installDeps.sh (avec root, `hash` perd la trace de node installé via nvm)
sudo chown admin -R "$final_path"
# Installe les dépendances de etherpad et procède à l'intallation.
"$final_path/bin/installDeps.sh" > $install_log 2>&1
sudo "$nodejs_path/npm" install forever -g >> $install_log 2>&1

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

sudo cp ../conf/settings.json "$final_path/settings.json"
sudo 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_replace_string "__PASSWD__" "$password" "$final_path/credentials.json"
if [ "$abiword" -eq 1 ]
then
	abiword_path=`which abiword`	# Récupère l'emplacement de l'exécutable de abiword
	ynh_replace_string "\"abiword\" : null" "\"abiword\" : \"$abiword_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"
ynh_store_checksum_config "$final_path/settings.json"	# Enregistre la somme de contrôle du fichier de config
ynh_store_checksum_config "$final_path/credentials.json"	# Enregistre la somme de contrôle du fichier de config


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

# Les fichiers appartiennent à etherpad
sudo chown -R $app: $final_path
sudo chmod 600 $final_path/credentials.json	# Restreint l'accès à credentials.json

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

ynh_systemd_config
ynh_replace_string "__NODEJS__" "$nodejs_use_version" "/etc/systemd/system/$app.service"
ynh_replace_string "__ENV_PATH__" "$PATH" "/etc/systemd/system/$app.service"
sudo systemctl daemon-reload

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

# Ajoute le service au monitoring de Yunohost.
sudo yunohost service add $app --log "/var/log/$app/etherpad.log"

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

script_dir="$PWD"
cd "$final_path"
sudo "$nodejs_path/npm" install ep_align >> $install_log 2>&1	# Add Left/Center/Right/Justify to lines of text in a pad
sudo "$nodejs_path/npm" install ep_author_hover >> $install_log 2>&1	# Framapad - Adds author names to span titles
sudo "$nodejs_path/npm" install ep_automatic_logut >> $install_log 2>&1	# Automatically disconnects user after some period of time (Prevent server overload)
sudo "$nodejs_path/npm" install ep_comments_page >> $install_log 2>&1	# Framapad - Adds comments on sidebar and link it to the text.
sudo "$nodejs_path/npm" install ep_countable >> $install_log 2>&1	# Framapad - Displays paragraphs, sentences, words and characters counts.
sudo "$nodejs_path/npm" install ep_delete_empty_pads >> $install_log 2>&1	# Framapad - Delete pads which were never edited
sudo "$nodejs_path/npm" install ep_font_color >> $install_log 2>&1	# Framapad - Apply colors to fonts
sudo "$nodejs_path/npm" install ep_headings2 >> $install_log 2>&1	# Framapad - Adds heading support to Etherpad Lite.
sudo "$nodejs_path/npm" install ep_markdown >> $install_log 2>&1	# Framapad - Edit and Export as Markdown in Etherpad
sudo "$nodejs_path/npm" install ep_mypads >> $install_log 2>&1	# Framapad - Groups and private pads for etherpad
sudo "$nodejs_path/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
sudo "$nodejs_path/npm" install ep_spellcheck >> $install_log 2>&1	# Framapad - Add support to do 'Spell checking'
sudo "$nodejs_path/npm" install ep_subscript_and_superscript >> $install_log 2>&1	# Framapad - Add support for Subscript and Superscript
sudo "$nodejs_path/npm" install ep_table_of_contents >> $install_log 2>&1	# Framapad - View a table of contents for your pad
# sudo "$nodejs_path/npm" install ep_unoconv"	# Framapad - Use unoconv instead of abiword to export pads.
sudo "$nodejs_path/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
sudo chown -R $app: $final_path/node_modules

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

# Ajoute un lien vers etherpad pour créer des pads anonymes depuis 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
# Et un lien vers l'admin etherpad depuis 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.
sudo 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.

#=================================================
# START ETHERPAD IN BACKGROUND
#=================================================

WARNING echo "Démarrage d'etherpad"
tempfile="$(mktemp)"
tail -f -n1 /var/log/$app/etherpad.log > "$tempfile" &	# Suit le démarrage dans le log
PID_TAIL=$!	# Récupère le PID de la commande tail, qui est passée en arrière plan.
sudo systemctl start $app	# Démarre etherpad. Le démarrage est fait le plus tôt possible, car il est très long...

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

if [ $is_public -eq 1 ]; then
	ynh_app_setting_set $app skipped_uris "/"
else
	ynh_app_setting_set $app skipped_uris "/admin"	# La page d'admin etherpad ne supporte pas le sso...
fi

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

sudo systemctl reload nginx

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

lang_OK=0
for i in `seq 1 120`
do	# La boucle attend le démarrage d'etherpad. Ou 2 minutes. Cette boucle évite simplement un 502 au début, car le démarrage est long...
	if grep -q "You can access your Etherpad instance at" "$tempfile" && [ "$lang_OK" -eq 0 ] ; then
		# Si le log annonce une première fois le démarrage d'etherpad, applique la langue de mypads et redémarre le service.
		WARNING echo "Le service $app a démarré correctement."
		ynh_replace_string "__LANGUAGE__" "$language" "$script_dir/../conf/lang_mypads.sql"
		mysql -u $db_name -p$db_pwd $db_name < "$script_dir/../conf/lang_mypads.sql"
		echo ""
		sudo systemctl restart $app
		cat /dev/null > "$tempfile"	# Purge le log de suivi du démarrage.
		lang_OK=1
		i=1;
	fi
	if grep -q "You can access your Etherpad instance at" "$tempfile" && [ "$lang_OK" -eq 1 ]; then
		WARNING echo "Le service $app a démarré correctement."
		break	# Si le log annonce une deuxième fois le démarrage d'etherpad, sort de la boucle.
	fi
	WARNING echo -n "."
	sleep 1
done
SUPPRESS_WARNING kill -s 15 $PID_TAIL	# Arrête l'exécution de tail.
ynh_secure_remove "$tempfile"