#!/bin/bash

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

source /usr/share/yunohost/helpers

#=================================================
# STOP SYSTEMD SERVICE
#=================================================
ynh_script_progression "Stopping $app's systemd service..."

ynh_systemctl --service="$app" --action="stop" --log_path="/var/log/$app/$app.log"

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

ynh_setup_source --dest_dir="$install_dir" --full_replace

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

#=================================================
# RE-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

#=================================================
# UPDATE A CONFIG FILE
#=================================================
ynh_script_progression "Updating $app's configuration files..."

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

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

ynh_config_add_nginx

ynh_config_add_systemd
yunohost service add "$app" --description="Jeu de géolocalisation OKI" --log="/var/log/$app/$app.log"

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 "Upgrade of $app completed"
