#!/bin/bash

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

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

#=================================================
# CHECK VERSION
#=================================================

upgrade_type=$(ynh_check_app_version_changed)

#=================================================
# STANDARD UPGRADE STEPS
#=================================================
# STOP SYSTEMD SERVICE
#=================================================
ynh_script_progression --message="Stopping a systemd service..." --weight=1

ynh_systemd_action --service_name="$app" --action="stop"

#=================================================
# ENSURE DOWNWARD COMPATIBILITY
#=================================================
ynh_script_progression --message="Ensuring downward compatibility..." --weight=1

if [ -n "${dns_over_https:-}" ] && [ "${dns_over_https:-}" == "1" ]; then
	dns_over_https="true"
	ynh_app_setting_set --app="$app" --key=dns_over_https --value=$dns_over_https
	# no need to open the ports, as they were opened at the 'Provisioning ports' step
elif [ -z "${dns_over_https:-}" ] || [ "${dns_over_https:-}" == "0" ]; then
	dns_over_https="false"
	ynh_app_setting_set --app="$app" --key=dns_over_https --value=$dns_over_https
	# if dns_over_https is false, we need to close ports,
    # as they were opened at the 'Provisioning ports' step
    ynh_exec_warn_less yunohost firewall disallow Both "$port_dns_over_http"
    ynh_exec_warn_less yunohost firewall disallow UDP "$port_dns_over_quic"
    ynh_exec_warn_less yunohost firewall reload
fi

# about all those 'ynh_replace_string':
# AGH modifies by itself the config file when an user modifies it using the front-end
# so if we're using 'ynh_add_config' to process the config file, each
# regeneration of the config would break the user's changes :/ (yeah ik...)
# maybe one day we'll use python3 -c "import yaml" in place of this shit, but not today

# fill the 'tls:' section of the AGH configuration if necessary
if grep -q "certificate_path: \"\"" "$install_dir/AdGuardHome.yaml" || grep -q "private_key_path: \"\"" "$install_dir/AdGuardHome.yaml" || grep -q "server_name: \"\"" "$install_dir/AdGuardHome.yaml"; then
	ynh_replace_string --match_string="enabled: \"\"" --replace_string="enabled: \"$dns_over_https\"" --target_file="$install_dir/AdGuardHome.yaml"
	# using sed magic because of the line break :/
	sed --in-place "/tls:$/{n;s/enabled: false/enabled: $dns_over_https/}" "$install_dir/AdGuardHome.yaml"
	ynh_replace_string --match_string="server_name: \"\"" --replace_string="server_name: $domain" --target_file="$install_dir/AdGuardHome.yaml"
	ynh_replace_string --match_string="allow_unencrypted_doh: false" --replace_string="allow_unencrypted_doh: true" --target_file="$install_dir/AdGuardHome.yaml"
	ynh_replace_string --match_string="certificate_path: \"\"" --replace_string="certificate_path: /etc/yunohost/certs/$domain/crt.pem" --target_file="$install_dir/AdGuardHome.yaml"
	ynh_replace_string --match_string="private_key_path: \"\"" --replace_string="private_key_path: /etc/yunohost/certs/$domain/key.pem" --target_file="$install_dir/AdGuardHome.yaml"
fi

# check if one of 'port_https:', 'port_dns_over_tls:' or 'port_dns_over_quic:' uses the default setting
if grep -q "port_https: 443" "$install_dir/AdGuardHome.yaml" || grep -q "port_dns_over_tls: 853" "$install_dir/AdGuardHome.yaml" || grep -q "port_dns_over_quic: 784" "$install_dir/AdGuardHome.yaml"; then
	# if so: mandatory replacement for them
	# (because the final user can't easily know the ports used by the package)
	ynh_replace_string --match_string="port_https: 443" --replace_string="port_https: $port_internal_https" --target_file="$install_dir/AdGuardHome.yaml"
	ynh_replace_string --match_string="port_dns_over_tls: 853" --replace_string="port_dns_over_tls: $port_dns_over_http" --target_file="$install_dir/AdGuardHome.yaml"
	ynh_replace_string --match_string="port_dns_over_quic: 784" --replace_string="port_dns_over_quic: $port_dns_over_quic" --target_file="$install_dir/AdGuardHome.yaml"
fi

if [ -n "${open_port_53:-}" ] && [ "${open_port_53:-}" == "1" ]; then
    open_port_53="true"
	ynh_app_setting_set --app="$app" --key=open_port_53 --value="$open_port_53"
	# if open_port_53 is true, we need to open port 53
    ynh_exec_warn_less yunohost firewall allow Both 53
    ynh_exec_warn_less yunohost firewall reload
elif [ -z "${open_port_53:-}" ] || [ "${open_port_53:-}" == "0" ]; then
    open_port_53="false"
	ynh_app_setting_set --app="$app" --key=open_port_53 --value="$open_port_53"
fi

# remove setting no longer required
ynh_app_setting_delete --app="$app" --key=port_adguard

#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================

if [ "$upgrade_type" == "UPGRADE_APP" ]
then
	ynh_script_progression --message="Upgrading source files..." --weight=1

	# Download, check integrity, uncompress and patch the source from app.src
	ynh_setup_source --dest_dir="$install_dir"
fi

chmod -R o-rwx "$install_dir"
chown -R "$app:$app" "$install_dir"

setcap 'CAP_NET_BIND_SERVICE=+eip CAP_NET_RAW=+eip' "$install_dir/AdGuardHome"

#=================================================
# NGINX CONFIGURATION
#=================================================
ynh_script_progression --message="Upgrading NGINX web server configuration..." --weight=1

# Create a dedicated NGINX config
ynh_add_nginx_config

# Create a dedicated systemd config
ynh_add_systemd_config

yunohost service add "$app" --description="Ads & trackers blocking DNS server" --needs_exposed_ports "$port_dns_over_http" "$port_dns_over_quic"

#=================================================
# SPECIFIC UPGRADE
#=================================================

# adding the adguardhome dedicated user to the 'ssl-cert' group to permit the
# use of the Let's Encrypt certs for DOT/DOQ
usermod -a -G ssl-cert "$app"

#=================================================
# UPDATE A CONFIG FILE
#=================================================
ynh_script_progression --message="Updating a configuration file..." --weight=1

ipv4_interface=$(echo "$(ip -4 route get 1.2.3.4 2> /dev/null)" | head -n1 | grep -oP '(?<=dev )\w+' || true)
ipv6_interface=$(echo "$(ip -6 route get ::1.2.3.4 2> /dev/null)" | head -n1 | grep -oP '(?<=dev )\w+' || true)

if [ -z "$ipv4_interface" ] && [ -z "$ipv6_interface" ]; then
		ynh_die --message="Impossible to find the main network interface, please report this issue."
elif [ "$ipv4_interface" != "$ipv6_interface" ]; then
		if [ -z "$ipv4_interface" ]; then
				echo -e "bind-interfaces\nexcept-interface=$ipv6_interface" > "/etc/dnsmasq.d/$app"
		elif [ -z "$ipv6_interface" ]; then
				echo -e "bind-interfaces\nexcept-interface=$ipv4_interface" > "/etc/dnsmasq.d/$app"
		else
				echo -e "bind-interfaces\nexcept-interface=$ipv4_interface, $ipv6_interface" > "/etc/dnsmasq.d/$app"
		fi
else
		echo -e "bind-interfaces\nexcept-interface=$ipv4_interface" > "/etc/dnsmasq.d/$app"
fi

systemctl restart dnsmasq

ynh_store_file_checksum --file="/etc/dnsmasq.d/$app"

# get IPv4 for the AGH config file
ipv4_addr=$(process_ips "$(ip -4 route get 1.2.3.4 2> /dev/null | head -n1 | head -n1)")

# get IPv6 for the AGH config file
ipv6_addr=$(process_ips "$(ip -6 route get ::1.2.3.4 2> /dev/null | head -n1)")

# update the IP adresses in the AGH config file
update_config

chmod 600 "$install_dir/AdGuardHome.yaml"
chown -R "$app:$app" "$install_dir/AdGuardHome.yaml"

#=================================================
# START SYSTEMD SERVICE
#=================================================
ynh_script_progression --message="Starting a systemd service..." --weight=1

ynh_systemd_action --service_name="$app" --action="restart" --log_path="systemd"

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

ynh_script_progression --message="Upgrade of $app completed" --last
