#!/bin/bash

#=================================================
# GENERIC START
#=================================================
# IMPORT GENERIC HELPERS
#=================================================

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

#=================================================
# APP "BUILD" (DEPLOYING SOURCES, VENV, COMPILING ETC)
#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================
ynh_script_progression --message="Setting up source files..." --weight=1

ynh_setup_source --dest_dir="$install_dir"

chown -R "$app:www-data" "$install_dir"

#=================================================
# SYSTEM CONFIGURATION
#=================================================
ynh_script_progression --message="Adding system configurations related to $app..." --weight=1

ynh_add_nginx_config

ynh_add_systemd_config

yunohost service add "$app" --description="Pydio - A file sharing platform" --log="/var/log/$app/$app.log"

# ynh_use_logrotate

# Create a dedicated Fail2Ban config
# ynh_add_fail2ban_config --logpath="/var/log/nginx/${domain}-error.log" --failregex="Regex to match into the log for a failed login"

#=================================================
# APP INITIAL CONFIGURATION
#=================================================
# ADD A CONFIGURATION
#=================================================
ynh_script_progression --message="Configuring Pydio..." --weight=1

ynh_add_config --template="install-conf.yml" --destination="$install_dir/install-conf.yml"

pushd "$install_dir" || ynh_die
	ynh_exec_as "$app" ./cells configure --cli --yaml "$install_dir/install-conf.yml"
popd || ynh_die

ynh_secure_remove --file="$install_dir/install-conf.yml"
ynh_delete_file_checksum --file="$install_dir/install-conf.yml"

#=================================================
# GENERIC FINALIZATION
#=================================================
# START SYSTEMD SERVICE
#=================================================
ynh_script_progression --message="Starting a systemd service..." --weight=1

ynh_systemd_action --service_name="$app" --action="start" --log_path="/var/log/$app/$app.log"

#=================================================
# END OF SCRIPT
#=================================================
ynh_script_progression --message="Installation of $app completed" --last