#!/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"

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

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

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

#=================================================
# 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 -U --upgrade-strategy eager pretix gunicorn
    $install_dir/venv/bin/python3 -m pretix migrate
    $install_dir/venv/bin/python3 -m pretix rebuild
    $install_dir/venv/bin/python3 -m pretix updateassets
popd

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

ynh_config_add_nginx

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

yunohost service add "${app}-web" --description="Ticket shop application" --log="/var/log/$app/$app.log"
yunohost service add "${app}-worker" --description="Pretix 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"
