#!/bin/bash

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

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

#=================================================
# LOAD SETTINGS
#=================================================
ynh_script_progression --message="Loading installation settings..."

app=$YNH_APP_INSTANCE_NAME

domain=$(ynh_app_setting_get --app=$app --key=domain)
path_url=$(ynh_app_setting_get --app=$app --key=path)
final_path=$(ynh_app_setting_get --app=$app --key=final_path)
port=$(ynh_app_setting_get --app=$app --key=port)
db_name=$(ynh_app_setting_get --app=$app --key=db_name)
db_user=$db_name
db_pwd=$(ynh_app_setting_get --app=$app --key=mysqlpwd)

#=================================================
# CHECK VERSION
#=================================================
ynh_script_progression --message="Checking version..."

upgrade_type=$(ynh_check_app_version_changed)

#=================================================
# ENSURE DOWNWARD COMPATIBILITY
#=================================================
ynh_script_progression --message="Ensuring downward compatibility..."

# If db_name doesn't exist, create it
if [ -z "$db_name" ]; then
	db_name=$(ynh_sanitize_dbid --db_name=$app)
	ynh_app_setting_set --app=$app --key=db_name --value=$db_name
fi

# Cleaning legacy permissions
if ynh_legacy_permissions_exists; then
	ynh_legacy_permissions_delete_all

	ynh_app_setting_delete --app=$app --key=is_public
fi

#=================================================
# BACKUP BEFORE UPGRADE THEN ACTIVE TRAP
#=================================================
ynh_script_progression --message="Backing up the app before upgrading (may take a while)..."

# Backup the current version of the app
ynh_backup_before_upgrade
ynh_clean_setup () {
	# restore it if the upgrade fails
	ynh_clean_check_starting
	ynh_restore_upgradebackup
}
# Exit if an error occurs during the execution of the script
ynh_abort_if_errors

#=================================================
# STANDARD UPGRADE STEPS
#=================================================
# STOP SYSTEMD SERVICE
#=================================================
ynh_script_progression --message="Stopping a systemd service..."

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

#=================================================
# CREATE DEDICATED USER
#=================================================
ynh_script_progression --message="Making sure dedicated system user exists..."

# Create a dedicated user (if not existing)
ynh_system_user_create --username=$app

#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================

if [ "$upgrade_type" == "UPGRADE_APP" ]
then
	ynh_script_progression --message="Upgrading source files..."

	# Create a temporary directory
	tmpdir="$(mktemp -d)"

	# Copy the admin saved settings from tmp directory to final path
	cp -ar "$final_path/config.production.json" "$tmpdir/config.production.json"

	# Backup the content folder to the temp dir
	cp -ar "$final_path/content" "$tmpdir/content"

	# Remove the app directory securely
	ynh_secure_remove --file=$final_path

	# Download, check integrity, uncompress and patch the source from app.src
	ynh_setup_source --dest_dir=$final_path

	# Download, check integrity, uncompress and patch the source from admin.src
	mkdir -p $final_path/core/client/Admin
	ynh_setup_source --dest_dir="$final_path/core/client/Admin" --source_id="admin"

	# Copy the admin saved settings from tmp directory to final path
	cp -ar "$tmpdir/config.production.json" "$final_path/config.production.json"

	# Copy content folder back to the final_path
	cp -ar "$tmpdir/content" "${final_path}"

	# Remove the tmp directory securely
	ynh_secure_remove --file="$tmpdir"
fi

#=================================================
# NGINX CONFIGURATION
#=================================================
ynh_script_progression --message="Upgrading NGINX web server configuration..."

# Create a dedicated nginx config
ynh_add_nginx_config

#=================================================
# UPGRADE DEPENDENCIES
#=================================================
ynh_script_progression --message="Upgrading dependencies..."

ynh_install_app_dependencies $pkg_dependencies

# Install Nodejs
ynh_exec_warn_less ynh_install_nodejs --nodejs_version=$NODEJS_VERSION

# Install Yarn
ynh_install_extra_app_dependencies --repo="deb https://dl.yarnpkg.com/debian/ stable main" --package="yarn" --key="https://dl.yarnpkg.com/debian/pubkey.gpg"

#=================================================
# SPECIFIC UPGRADE
#=================================================
# MODIFY A CONFIG FILE
#=================================================
ynh_script_progression --message="Modifying a config file..."

ynh_add_config --template="../conf/config.production.json" --destination="$final_path/config.production.json"

#==============================================
# BUILD GHOST
#==============================================
if [ "$upgrade_type" == "UPGRADE_APP" ]
then
	ynh_script_progression --message="Building $app... (this will take some time and resources!)"

	pushd "$final_path" || ynh_die
		ynh_exec_warn_less yarn install
		ynh_exec_warn_less yarn global add knex-migrator
		ynh_exec_warn_less NODE_ENV=production knex-migrator init
		ynh_exec_warn_less yarn global add grunt
		ynh_exec_warn_less NODE_ENV=production grunt symlink
		ynh_exec_warn_less NODE_ENV=production grunt init --force

	popd || ynh_die
fi

#=================================================
# SETUP SYSTEMD
#=================================================
ynh_script_progression --message="Upgrading systemd configuration..."

# Create a dedicated systemd config
 ynh_add_systemd_config
 
#=================================================
# GENERIC FINALIZATION
#=================================================
# SECURE FILES AND DIRECTORIES
#=================================================
ynh_script_progression --message="Securing files and directories..."

# Set permissions on app files
chown -R $app: $final_path

#=================================================
# INTEGRATE SERVICE IN YUNOHOST
#=================================================
ynh_script_progression --message="Integrating service in YunoHost..."

yunohost service add $app --description="$app daemon for Ghost" --log="/var/log/$app/$app.log"

#=================================================
# START SYSTEMD SERVICE
#=================================================
ynh_script_progression --message="Starting a systemd service..."

ynh_systemd_action --service_name=$app --action=start --log_path=systemd --line_match="Ghost boot"

#=================================================
# RELOAD NGINX
#=================================================
ynh_script_progression --message="Reloading NGINX web server..."

ynh_systemd_action --service_name=nginx --action=reload

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

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