#!/bin/bash

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

source ../settings/scripts/_common.sh
source /usr/share/yunohost/helpers
# Load common variables for all scripts.
source ../settings/scripts/_variables

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

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

#=================================================
# LOAD SETTINGS
#=================================================

app=$YNH_APP_INSTANCE_NAME

domain=$(ynh_app_setting_get $app domain)
path_url=$(ynh_app_setting_get $app path)
final_path=$(ynh_app_setting_get $app final_path)
enable_dhcp=$(ynh_app_setting_get $app enable_dhcp)
admin=$(ynh_app_setting_get $app admin)

#=================================================
# CHECK IF THE APP CAN BE RESTORED
#=================================================

ynh_webpath_available $domain $path_url \
	|| ynh_die "Path not available: ${domain}${path_url}"
test ! -d $final_path \
	|| ynh_die "There is already a directory: $final_path "

#=================================================
# ACTIVATE MAINTENANCE MODE
#=================================================

ynh_maintenance_mode_ON

#=================================================
# STANDARD RESTORE STEPS
#=================================================
# RESTORE THE NGINX CONFIGURATION
#=================================================

ynh_restore_file "/etc/nginx/conf.d/$domain.d/$app.conf"

#=================================================
# RESTORE THE MAIN DIRECTORIES OF THE APP
#=================================================

ynh_restore_file "$final_path"

ynh_restore_file "/etc/.pihole"

ynh_restore_file "/etc/pihole"

ynh_restore_file "/opt/pihole"

#=================================================
# RECREATE THE DEDICATED USER
#=================================================

# Create the dedicated user (if not existing)
ynh_system_user_create $app

#=================================================
# RESTORE USER RIGHTS
#=================================================

# Restore permissions on app files
chown $app: -R "/etc/pihole"

#=================================================
# RESTORE THE PHP-FPM CONFIGURATION
#=================================================

ynh_restore_file "/etc/php5/fpm/pool.d/$app.conf"

#=================================================
# SPECIFIC RESTORE
#=================================================
# REINSTALL DEPENDENCIES
#=================================================

ynh_install_app_dependencies $app_depencencies

#=================================================
# ADVERTISE SERVICE IN ADMIN PANEL
#=================================================

yunohost service add pihole-FTL --log "/var/log/pihole-FTL.log"

#=================================================
# RESTORE THE CRON FILE
#=================================================

ynh_restore_file "/etc/cron.d/pihole"

#=================================================
# RECREATE LOG FILES
#=================================================

touch /var/log/pihole.log
chmod 644 /var/log/pihole.log
dnsmasq_user=$(grep DNSMASQ_USER= /etc/init.d/dnsmasq | cut -d'"' -f2)
chown $dnsmasq_user:root /var/log/pihole.log

#=================================================
# RESTORE SPECIFIC FILES
#=================================================

ynh_restore_file "/usr/local/bin/pihole"
ynh_restore_file "/etc/bash_completion.d/pihole"

ynh_restore_file "/etc/sudoers.d/pihole"

ynh_restore_file "/etc/init.d/pihole-FTL"
ynh_restore_file "/usr/bin/pihole-FTL"

ynh_restore_file "/usr/share/yunohost/hooks/conf_regen/50-dnsmasq_$app"

#=================================================
# RESTORE DNSMASQ CONFIG
#=================================================

ynh_systemd_action --action=stop --service_name=dnsmasq

ynh_restore_file "/etc/dnsmasq.d/01-pihole.conf"
test -e "${YNH_APP_BACKUP_DIR}/etc/dnsmasq.d/02-pihole-dhcp.conf" && \
	ynh_restore_file "/etc/dnsmasq.d/02-pihole-dhcp.conf"
test -e "${YNH_APP_BACKUP_DIR}/etc/dnsmasq.d/03-pihole-wildcard.conf" && \
	ynh_restore_file "/etc/dnsmasq.d/03-pihole-wildcard.conf"
test -e "${YNH_APP_BACKUP_DIR}/etc/dnsmasq.d/04-pihole-static-dhcp.conf" && \
	ynh_restore_file "/etc/dnsmasq.d/04-pihole-static-dhcp.conf"

# To prevent any conflict with the original dnsmasq config, comment cache-size in the original config.
ynh_replace_string "^cache-size=" "#pihole# cache-size=" /etc/dnsmasq.conf

#=================================================
# CONFIGURE DNS FOR THE LOCAL DOMAINS
#=================================================

# Get the default network interface
main_iface=$(ip route | grep default | awk '{print $5;}')
# Find the IP associated to the network interface
localipv4=$(ip address | grep "${main_iface}\$" | awk '{print $2;}' | cut -d/ -f1)

# List all YunoHost domains
while read perdomain
do
	# Comment domain resolution in /etc/hosts on 127.0.0.1, because they can interfere with the local network resolution.
	sed -i "s/^127.0.0.1.*$perdomain/#Commented by pihole# &/g" /etc/hosts

	# And add a resolution on the local IP instead
	grep -q "^$localipv4.*$perdomain" /etc/hosts || \
		echo "$localipv4	$perdomain #Added by pihole#" >> /etc/hosts
done <<< "$(yunohost domain list | grep "\." | sed 's/.*: \|.*- //')"

#=================================================
# RESTART DNSMASQ
#=================================================

ynh_systemd_action --action=restart --service_name=dnsmasq

#=================================================
# UPDATE VARIABLES FILE
#=================================================

setupVars="/etc/pihole/setupVars.conf"

echo "PIHOLE_INTERFACE=$main_iface" > $setupVars
ynh_replace_string "^PIHOLE_INTERFACE=.*" "PIHOLE_INTERFACE=$main_iface" $setupVars
ynh_replace_string "^IPV4_ADDRESS=.*" "IPV4_ADDRESS=127.0.0.1" $setupVars

# Recalculate and store the checksum of the file for the next upgrade.
ynh_store_file_checksum "$setupVars"

#=================================================
# START PIHOLE-FTL
#=================================================

ynh_exec_warn_less systemctl enable pihole-FTL
ynh_systemd_action --action=restart --service_name=pihole-FTL

#=================================================
# GENERIC FINALISATION
#=================================================
# RELOAD NGINX AND PHP-FPM
#=================================================

ynh_systemd_action --action=reload --service_name=php5-fpm
ynh_systemd_action --action=reload --service_name=nginx

#=================================================
# DEACTIVE MAINTENANCE MODE
#=================================================

ynh_maintenance_mode_OFF

#=================================================
# SEND A README FOR THE ADMIN
#=================================================

# Get main domain and buid the url of the admin panel of the app.
admin_panel="https://$(grep portal_domain /etc/ssowat/conf.json | cut -d'"' -f4)/yunohost/admin/#/apps/$app"

if [ $enable_dhcp -eq 1 ]
then
	dhcp_alert="You asked to use the internal DHCP server of dnsmasq with PiHole.
You should really read the documentation about that, https://github.com/YunoHost-Apps/pihole_ynh/blob/master/dhcp.md

"
else
	dhcp_alert=""
fi

message="${dhcp_alert}You can configure this app easily by using the experimental config-panel feature: $admin_panel/config-panel.
You can also find some specific actions for this app by using the experimental action feature: $admin_panel/actions.

If you're facing an issue or want to improve this app, please open a new issue in this project: https://github.com/YunoHost-Apps/pihole_ynh"

ynh_send_readme_to_admin --app_message="$message" --recipients="$admin" --type="restore"
