#!/bin/bash

#=================================================
# GENERIC START
#=================================================

# Load common variables and helpers
source ../settings/scripts/_common.sh
source /usr/share/yunohost/helpers

#=================================================
# RESTORE THE APP MAIN DIR
#=================================================
ynh_script_progression "Restoring the app files..."
ynh_restore_everything
_set_permissions

#=================================================
# RESTORE THE MYSQL DATABASE
#=================================================
ynh_script_progression "Restoring the MySQL database..."

ynh_mysql_db_shell < ./db.sql

#=================================================
# RESTORE SYSTEM CONFIGURATIONS
#=================================================
ynh_script_progression "Restoring system configurations related to $app..."

systemctl daemon-reload
systemctl enable "$app".service --quiet

yunohost service add "$app" --log="/var/log/$app/gitea.log"

# SETUP FAIL2BAN
ynh_script_progression "Configuring fail2ban..."
ynh_config_add_fail2ban --logpath="/var/log/$app/gitea.log" --failregex=".*Failed authentication attempt for .* from <HOST>"

mkdir -p /var/log/"$app"
ynh_config_add_logrotate

#=================================================
# RELOAD NGINX AND PHP-FPM OR THE APP SERVICE
#=================================================
ynh_script_progression "Reloading NGINX web server and $app's service..."

# Typically you only have either $app or php-fpm but not both at the same time...
ynh_systemctl --service="$app" --action=start --log_path="/var/log/$app/gitea.log" --wait_until="$systemd_match_start_line"

ynh_systemctl --service=nginx --action=reload

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

ynh_script_progression "Restoration completed for $app"