#!/bin/bash

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

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

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

ynh_systemctl --service="${app}-web" --action="stop" --log_path="systemd"
ynh_systemctl --service="${app}-worker" --action="stop" --log_path="systemd"

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

mkdir -p $install_dir

chmod 750 "$install_dir"
chmod -R o-rwx "$install_dir"
chown -R $app:www-data "$install_dir"

#=================================================
# INSTALL PYTHON DEPENDENCIES
#=================================================
ynh_script_progression "Installing Python dependencies..."

pushd $install_dir
    python3 -m venv $install_dir/venv
    ynh_hide_warnings $install_dir/venv/bin/pip install pip setuptools wheel gunicorn
    ynh_hide_warnings $install_dir/venv/bin/pip install --upgrade-strategy eager -U "pretalx[postgres]"
    ynh_hide_warnings $install_dir/venv/bin/python3 -m pretalx migrate
    ynh_hide_warnings $install_dir/venv/bin/python3 -m pretalx rebuild
    ynh_hide_warnings $install_dir/venv/bin/python3 -m pretalx updateassets
popd

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

ynh_config_add --template="pretalx.cfg" --destination="$install_dir/pretalx.cfg"

chmod 600 "$install_dir/pretalx.cfg"
chown "$app:$app" "$install_dir/pretalx.cfg"

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

ynh_config_add_nginx

ynh_config_add_systemd --service="${app}-web" --template="pretalx-web.service"
ynh_config_add_systemd --service="${app}-worker" --template="pretalx-worker.service"

yunohost service add "${app}-web" --description="Conference management application" --log="/var/log/$app/$app.log"
yunohost service add "${app}-worker" --description="Pretalx worker" --log="/var/log/$app/$app.log"

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

ynh_systemctl --service="${app}-web" --action="start" --log_path="systemd"
ynh_systemctl --service="${app}-worker" --action="start" --log_path="systemd"

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

ynh_script_progression "Upgrade of $app completed"
