#!/bin/bash

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

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

#=================================================
# MANAGE SCRIPT FAILURE
#=================================================

# Exit if an error occurs during the execution of the script
ynh_abort_if_errors

app=$YNH_APP_INSTANCE_NAME
db_user=$app
db_name=$app

# retrieve useful param
domain=$(ynh_app_setting_get $app domain)
path=$(ynh_app_setting_get $app path)

# Check web path availability
ynh_webpath_available $domain $path
# Register (book) web path
ynh_webpath_register $app $domain $path

db_pass=$(ynh_app_setting_get $app mysqlpwd)

#install php dependencies if necessary
install_freshrss_dependencies

# Restore sources & data
final_path=/var/www/$app
ynh_restore_file "$final_path"

# Restore permissions
sudo chown -R root:root $final_path
sudo chown -R www-data: $final_path/data/
sudo chown -R www-data: $final_path/extensions/

# Restore conf files
ynh_restore_file "/etc/nginx/conf.d/$domain.d/$app.conf"
ynh_restore_file "/etc/cron.d/$app"
ynh_restore_file "/etc/php/7.0/fpm/pool.d/$app.conf"

# Restore mysql dump
ynh_mysql_create_db "$db_name" "$db_user" "$db_pass"
ynh_mysql_connect_as "$db_user" "$db_pass" "$db_name" < "$app.dmp"

# Reload Nginx, and regenerate SSOwat conf
sudo service nginx reload
sudo service php7.0-fpm reload
sudo yunohost app ssowatconf