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

domain=$YNH_APP_ARG_DOMAIN
is_public=$YNH_APP_ARG_IS_PUBLIC
path_url=$YNH_APP_ARG_PATH # Assure la compatibilité avec les fonctions utilisant $path_url
app=$YNH_APP_INSTANCE_NAME
secret=$(ynh_string_random)

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

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 is_public $is_public
ynh_app_setting_set "$app" secret "$secret"

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

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

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

ynh_install_app_dependencies mongodb
systemctl start mongodb

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

dbname=$app
dbuser=$app
dbpass=$(ynh_string_random)
ynh_app_setting_set $app dbuser $dbuser
ynh_app_setting_set $app dbpass $dbpass
ynh_app_setting_set $app dbname $dbname
mongo --shell "$dbname" --eval 'db.createUser( { user: "'${dbuser}'", pwd: "'${dbpass}'", roles: [ "readWrite" ] } );' <<< exit
mongo --shell "$dbname" --eval 'db.grantRolesToUser("'${dbuser}'",[{ role: "clusterMonitor", db: "admin" }]);' <<< exit

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

ynh_install_nodejs 8.14.0

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

# Create a system user
ynh_system_user_create $app

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

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

# Configuration de logrotate
ynh_use_logrotate

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

final_path=/var/www/$app
ynh_app_setting_set $app final_path $final_path
ynh_setup_source "$final_path"	# Télécharge la source, décompresse et copie dans $final_path

#=================================================
# Modify Nginx configuration file and copy it to Nginx conf directory
#=================================================

ynh_add_nginx_config

#=================================================
# Add Systemd service
#=================================================

ynh_add_systemd_config
ynh_replace_string "__ENV_PATH__" "$PATH" "/etc/systemd/system/$app.service"
ynh_replace_string "__NODE__" "$nodejs_path" "/etc/systemd/system/$app.service"
cat /etc/systemd/system/$app.service

#=================================================
# CONFIGURE SERVER.JS	
#=================================================

mv ../conf/config.json $final_path/config.json
ynh_replace_string "__URL__" "$domain" "$final_path/config.json"
ynh_replace_string "__PORT__" "$port" "$final_path/config.json"
ynh_replace_string "__SECRET__" "$secret" "$final_path/config.json"
ynh_replace_string "dbuser" "$dbuser" "$final_path/config.json"
ynh_replace_string "dbname" "$dbname" "$final_path/config.json"
ynh_replace_string "dbpass" "$dbpass" "$final_path/config.json"
cat $final_path/config.json

#=================================================
# CONFIGURE NODEBB
#=================================================

chown -R $app:$app $final_path
pushd $final_path
exec_as "$app" PATH=$PATH ./nodebb setup -l > $install_log
exec_as "$app" PATH=$PATH npm install nodebb-plugin-dbsearch --save-prod
exec_as "$app" PATH=$PATH ./nodebb build -l
popd


#=================================================
# START NodeBB IN BACKGROUND
#=================================================

cat /etc/systemd/system/$app.service
sudo systemctl daemon-reload
sudo systemctl enable "$app".service

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

systemctl start $app     # Démarre Nodebb. Le démarrage est fait le plus tôt possible, car il est très long...

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

yunohost service add $app --log "/var/log/$app/nodebb.log"

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

if [ $is_public -eq 0 ]
then	# Remove the public access
	ynh_app_setting_delete $app skipped_uris
fi
# Make app public if necessary
if [ $is_public -eq 1 ]
then
	# unprotected_uris allows SSO credentials to be passed anyway.
	ynh_app_setting_set $app unprotected_uris "/"
fi
ynh_check_starting "NodeBB is now listening on: 0.0.0.0:4567" "/var/log/syslog" "90"

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

systemctl reload nginx

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

mail_content=$(cat $install_log | grep '\(Username\|Password\)')*

message=" $app was successfully installed :)
Please open your $app domain: https://$domain$path_url

$mail_content

If you are facing any problem or want to improve this app, please open a new issue here: https://github.com/YunoHost-Apps/nodebb_ynh"

ynh_send_readme_to_admin "$message"