#!/bin/bash

#=================================================
# GENERIC STARTING
#=================================================
# IMPORT GENERIC HELPERS
#=================================================

source scripts/_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

#=================================================
# RETRIEVE ARGUMENTS
#=================================================

app=$YNH_APP_INSTANCE_NAME

query_logging=$(ynh_app_setting_get --app=$app --key=query_logging)

#=================================================
# SORT OUT THE CONFIG FILE TO HANDLE
#=================================================

file="$1"

if [ "$file" = "setupVars.conf" ]; then
    config_file="/etc/pihole/setupVars.conf"
elif [ "$file" = "pihole-FTL.conf" ]; then
    config_file="/etc/pihole/pihole-FTL.conf"
fi

#=================================================
# SPECIFIC ACTION
#=================================================
# RESET THE CONFIG FILE
#=================================================
ynh_script_progression --message="Resetting the config file $config_file..." --weight=9

# Verify the checksum and backup the file if it's different
ynh_backup_if_checksum_is_different --file="$config_file"

main_iface=$(ip route | grep --max-count=1 default | awk '{print $5;}')

if [ "$file" = "setupVars.conf" ]
then
    # Recreate the default config
    # Trouve l'interface réseau par défaut
    echo "PIHOLE_INTERFACE=$main_iface" > "$config_file"
    echo "IPV4_ADDRESS=127.0.0.1" >> "$config_file"
    echo "IPV6_ADDRESS=::1" >> "$config_file"
    echo "PIHOLE_DNS_1=" >> "$config_file"
    echo "PIHOLE_DNS_2=" >> "$config_file"
    if [ $query_logging -eq 1 ]; then
        query_logging=true
    else
        query_logging=false
    fi
    echo "QUERY_LOGGING=$query_logging" >> "$config_file"
    echo "INSTALL_WEB=true" >> "$config_file"

elif [ "$file" = "pihole-FTL.conf" ]
then
    # Get the default file and overwrite the current config
    port=$(ynh_app_setting_get --app=$app --key=port)
    ynh_add_config --template="/etc/yunohost/apps/$app/conf/pihole-FTL.conf" --destination="$config_file"

    ynh_script_progression --message="Restarting Pi-Hole..." --weight=2

    # Restart pihole-FTL
    ynh_systemd_action --action=restart --service_name=pihole-FTL
fi

# Calculate and store the config file checksum into the app settings
ynh_store_file_checksum --file="$config_file"

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

ynh_script_progression --message="Execution completed" --last
