#!/bin/bash

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

if [ ! -e _common.sh ]; then
	# Get the _common.sh file if it's not in the current directory
	cp ../settings/scripts/_common.sh ./_common.sh
	chmod a+rx _common.sh
fi
source _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 "

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

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

#=================================================
# RESTORE OF 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 OF THE DEDICATED USER
#=================================================

ynh_system_user_create $app	# Recreate the dedicated user, if not exist

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

# Les fichiers appartiennent à root
chown $app: -R "/etc/pihole"

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

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

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

ynh_install_app_dependencies $app_depencencies

#=================================================
# ENABLE SERVICE IN ADMIN PANEL
#=================================================

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

#=================================================
# RESTORE OF 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 OF 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 OF DNSMASQ CONFIG
#=================================================

ynh_system_reload dnsmasq stop

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"

# Pour éviter un conflit entre les config de dnsmasq, il faut commenter cache-size dans la config par défaut.
ynh_replace_string "^cache-size=" "#pihole# cache-size=" /etc/dnsmasq.conf

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

# Trouve l'interface réseau par défaut
main_iface=$(route | grep default | awk '{print $8;}' | head -n1)
# Trouve l'ipv4 associée à l'interface trouvée
localipv4=$(ifconfig | grep -A 1 "$main_iface" | tail -1 | awk '{print $2;}' | cut -d: -f2)

# Liste les domaines de yunohost
while read perdomain
do
	# Commente les résolutions du domaine sur 127.0.0.1, qui risquerait de bloquer la résolution sur le réseau local
	sed -i "s/^127.0.0.1.*$perdomain/#Commented by pihole# &/g" /etc/hosts

	# Et ajoute une résolution sur l'ip local à la place, si elle n'existe pas déjà
	grep -q "^$localipv4.*$perdomain" /etc/hosts || \
		echo "$localipv4	$perdomain #Added by pihole#" >> /etc/hosts
done <<< "$(yunohost domain list | grep "\." | sed 's/.*: \|.*- //')"

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

ynh_system_reload dnsmasq restart

#=================================================
# UPDATE THE 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

ynh_store_file_checksum "$setupVars"	# Enregistre la somme de contrôle du fichier de config

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

ynh_exec_warn_less systemctl enable pihole-FTL
ynh_system_reload pihole-FTL restart

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

ynh_system_reload php5-fpm
ynh_system_reload nginx

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

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}If you 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 "$message" "$admin"
