#!/bin/bash

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

source /usr/share/yunohost/helpers

#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================
ynh_script_progression "Setting up source files..."

ynh_setup_source --dest_dir="$install_dir"

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

#=================================================
# BUILD THE APP
#=================================================
ynh_script_progression "Building $app (this may take a few minutes)..."

pushd "$install_dir/app"
	ynh_hide_warnings ynh_exec_as_app npm ci
	ynh_hide_warnings ynh_exec_as_app npm run build
	ynh_hide_warnings ynh_exec_as_app npm prune --omit=dev
popd

#=================================================
# APP INITIAL CONFIGURATION
#=================================================
ynh_script_progression "Adding $app's configuration files..."

ynh_config_add --template="env" --destination="$install_dir/app/.env"

#=================================================
# SYSTEM CONFIGURATION
#=================================================
ynh_script_progression "Adding system configurations related to $app..."

# Create a dedicated NGINX config using the conf/nginx.conf template
ynh_config_add_nginx

# Create a dedicated systemd config
ynh_config_add_systemd
yunohost service add "$app" --description="Jeu de géolocalisation OKI" --log="/var/log/$app/$app.log"

# Use logrotate to manage application logfile(s)
mkdir -p "/var/log/$app"
chown -R "$app:$app" "/var/log/$app"
ynh_config_add_logrotate

#=================================================
# START SYSTEMD SERVICE
#=================================================
ynh_script_progression "Starting $app's systemd service..."

ynh_systemctl --service="$app" --action="start" --wait_until="Listening" --log_path="/var/log/$app/$app.log"

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

ynh_script_progression "Installation of $app completed"
