#!/bin/bash

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

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

#=================================================
# INSTALL BORG
#=================================================
ynh_script_progression --message="Reinstalling Borg..."

install_borg_with_pip

_gen_and_save_public_key

mkdir -p "/var/log/$app"
chown -R $app:$app "/var/log/$app"
chmod u+w "/var/log/$app"

#=================================================
# ACTIVATE BACKUP METHODS
#=================================================
ynh_script_progression --message="Setting up backup method..." --weight=1

mkdir -p /etc/yunohost/hooks.d/backup
mkdir -p /etc/yunohost/hooks.d/backup_method
mkdir -p /usr/share/yunohost/backup_method

ynh_restore_file --origin_path="/etc/yunohost/hooks.d/backup_method/05-${app}_app"
chmod go=--- "/etc/yunohost/hooks.d/backup_method/05-${app}_app"

ynh_restore_file --origin_path="/etc/sudoers.d/$app"
chown root:root "/etc/sudoers.d/$app"

ynh_restore_file --origin_path="$install_dir/backup-with-borg"
chmod u+x "$install_dir/backup-with-borg"
chown "$app:$app" "$install_dir/backup-with-borg"

ynh_restore_file --origin_path="$install_dir/logging.conf"
chown "$app:$app" "$install_dir/logging.conf"

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

ynh_restore_file --origin_path="/etc/systemd/system/$app.service"
yunohost service add $app --description="Deduplicating backup program" --test_status="systemctl show $app.service  -p ActiveState --value | grep -v failed" --log "/var/log/$app/borg.log"
# Disable the service, this is to prevent the service from being triggered at boot time
systemctl disable $app.service --quiet

ynh_restore_file --origin_path="/etc/systemd/system/$app.timer"
systemctl enable $app.timer --quiet
systemctl start $app.timer

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

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