#!/bin/bash

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

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

upgrade_type=$(ynh_check_app_version_changed)

upstream_source_url=$(ynh_read_manifest --manifest_key="resources.sources.main.url")
source_filename=$(basename $upstream_source_url)
index_page=$(basename -s .zip $upstream_source_url).html #this variable will also populate the template tag __INDEX_PAGE__ in nginx.conf

#=================================================
# "REBUILD" THE APP (DEPLOY NEW SOURCES, RERUN NPM BUILD, ETC...)
#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================

if [ "$upgrade_type" == "UPGRADE_APP" ]
then
	ynh_script_progression --message="Upgrading source files..." --weight=10
	ynh_setup_source --dest_dir="$install_dir" --full_replace=1
	ynh_replace_string --match_string="$source_filename" --replace_string="$upstream_source_url" --target_file="$install_dir/$index_page" #replace link to local source file with link to upstream source file 
	chown -R $app:www-data "$install_dir"
fi

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

#=================================================
# REAPPLY SYSTEM CONFIGURATIONS
#=================================================
ynh_script_progression --message="Upgrading system configurations related to $app..." --weight=4

ynh_add_nginx_config

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

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