#!/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 --message="Restoring the app files..." --weight=1
ynh_restore
_set_permissions

#=================================================
# RESTORE THE MYSQL DATABASE
#=================================================
ynh_script_progression --message="Restoring the MySQL database..." --weight=1

ynh_mysql_connect_as --user="$db_user" --password="$db_pwd" --database="$db_name" < ./db.sql

#=================================================
# RESTORE SYSTEM CONFIGURATIONS
#=================================================
ynh_script_progression --message="Restoring system configurations related to $app..." --weight=1

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

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

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

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

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

ynh_systemd_action --service_name=nginx --action=reload

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

ynh_script_progression --message="Restoration completed for $app" --last