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

ynh_setup_source --dest_dir="$install_dir"

chown -R $app:www-data "$install_dir"
find "$install_dir" -type f -exec chmod 640 {} \;
find "$install_dir" -type d -exec chmod 750 {} \;
find "$install_dir" -type d -exec chmod +s {} \;

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

ynh_add_fpm_config --usage=low --footprint=low

ynh_add_nginx_config

ynh_use_logrotate

#=================================================
# APP INITIAL CONFIGURATION
#=================================================
# SETUP APPLICATION WITH CURL
#=================================================
ynh_script_progression --message="Finalizing installation..." --weight=1

installLanguage="$language"
installUrl="/?install/postinstall/$installLanguage"
installId="$admin"
installPassword="${password}"
installMail=$(ynh_user_get_info --username="$admin" --key=mail)
installFirstname=$(ynh_user_get_info --username="$admin" --key=fullname | awk  -F' ' '{print $1}')
installLastname=$(ynh_user_get_info --username="$admin" --key=fullname | awk  -F' ' '{print $2}')

csrf=$(ynh_local_curl "${installUrl}" | grep "csrf" | awk -F'value="' '{print $2}' | awk -F'"' '{print $1}')

ynh_local_curl "${installUrl}" "csrf=${csrf}" "installId=${installId}" "installPassword=${installPassword}" "installConfirmPassword=${installPassword}" "installMail=${installMail}" "installFirstname=${installFirstname}" "installLastname=${installLastname}" "installLanguage=${installLanguage}"

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

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