#!/bin/bash

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

#=================================================
# STANDARD RESTORATION STEPS
#=================================================
# RESTORE THE NGINX CONFIGURATION
#=================================================
ynh_script_progression "Restoring the NGINX web server configuration..."

ynh_restore "/etc/nginx/conf.d/$domain.d/$app.conf"

#=================================================
# RESTORE THE APP MAIN DIR
#=================================================
ynh_script_progression "Restoring $app main directory..."

ynh_restore "$install_dir"
ynh_restore "$data_dir"

# See conf/gunicorn.conf.py
if [ -f "$data_dir/gunicorn.pid" ]; then ynh_safe_rm "$data_dir/gunicorn.pid"; fi

ynh_script_progression "Set $app file permissions..."
myynh_fix_file_permissions

#=================================================
# PYTHON VIRTUALENV
# Maybe the backup contains a other Python version
#=================================================

ynh_script_progression "Setup Python virtualenv for $app ..."
myynh_setup_python_venv

#=================================================
# RESTORE THE PostgreSQL DATABASE
#=================================================
ynh_script_progression "Restoring the PostgreSQL database..."

ynh_psql_db_shell < ./db.sql

#=================================================
# RESTORE SYSTEMD
#=================================================
ynh_script_progression "Restoring the systemd $app configuration..."

ynh_restore "/etc/systemd/system/$app.service"
systemctl enable $app.service --quiet

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

yunohost service add --description $app $app

#=================================================
# RESTORE THE LOGROTATE CONFIGURATION
#=================================================
ynh_script_progression "Setup logging..."

myynh_setup_log_file
ynh_restore "/etc/logrotate.d/$app"

#=================================================
# SECURE FILES AND DIRECTORIES
#=================================================
ynh_script_progression "Set $app file permissions..."
myynh_fix_file_permissions

#=================================================
# START APP
#=================================================
ynh_script_progression "Starting systemd service '$app'..."

ynh_systemctl --service=$app --action="start" --log_path="$log_file"

#=================================================
# RELOAD NGINX
#=================================================
ynh_script_progression "Reloading nginx web server..."

ynh_systemctl --service="nginx" --action="reload"

#=================================================
# END OF SCRIPT
#=================================================
ynh_script_progression "Restoration completed for $app"
