#!/bin/bash

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

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

#=================================================
# INITIALIZE AND STORE SETTINGS
#=================================================

ynh_app_setting_set --app="$app" --key="overwrite_setupvars" --value=1
ynh_app_setting_set --app="$app" --key="overwrite_ftl" --value=1

#=================================================
# CHECK AVAILABLE PORT
#=================================================

_configure_ports

#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================
ynh_script_progression --message="Setting up source files..." --weight=4

# Download, check integrity, uncompress and patch the source from app.src
ynh_setup_source --dest_dir="$PI_HOLE_LOCAL_REPO"
ynh_setup_source --source_id="pi-hole_web" --dest_dir="$install_dir/web"
ynh_setup_source --source_id="pi-hole_ftl" --dest_dir="$install_dir/ftl"

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

touch /var/log/{pihole,pihole-FTL}.log
chmod 644 /var/log/{pihole,pihole-FTL}.log
chown "$dnsmasq_user:root" /var/log/{pihole,pihole-FTL}.log

#=================================================
# INSTALLATION OF PIHOLE-FTL
#=================================================
ynh_script_progression --message="Building PiHole-FTL..." --weight=30

# -------------------------------------------------
# Build & install mbedTLS >= 3.x (required for FTL v6 on Debian 12)
# -------------------------------------------------
mbedtls_dir="$install_dir/mbedtls"
ynh_setup_source --source_id="mbedtls" --dest_dir="$mbedtls_dir"

# Enable pthread support (required by Pi-hole)
sed -i '/#define MBEDTLS_THREADING_C/s@^//@@' "$mbedtls_dir/include/mbedtls/mbedtls_config.h"
sed -i '/#define MBEDTLS_THREADING_PTHREAD/s@^//@@' "$mbedtls_dir/include/mbedtls/mbedtls_config.h"

pushd "$mbedtls_dir"
    ynh_exec_warn_less make -j"$(nproc)"
    ynh_exec_warn_less make install
popd

ldconfig

# -------------------------------------------------
# Build Pi-hole FTL against /usr/local (mbedTLS 3.x)
# -------------------------------------------------
export CMAKE_PREFIX_PATH="/usr/local:${CMAKE_PREFIX_PATH:-}"
export CPATH="/usr/local/include:${CPATH:-}"
export LIBRARY_PATH="/usr/local/lib:${LIBRARY_PATH:-}"
export LD_LIBRARY_PATH="/usr/local/lib:${LD_LIBRARY_PATH:-}"

pushd "$install_dir/ftl"
    ynh_exec_warn_less cmake .
    ynh_exec_warn_less make -j"$(nproc)"
    ynh_exec_warn_less make install
popd

ynh_secure_remove --file="$install_dir/ftl"
ynh_secure_remove --file="$mbedtls_dir"


#=================================================
# INSTALL THE SCRIPTS
#=================================================
ynh_script_progression --message="Installing Pihole..." --weight=1

install -o "$app" -Dm755 -d "$PI_HOLE_INSTALL_DIR"
install -o "$app" -Dm755 -t "$PI_HOLE_INSTALL_DIR" "$PI_HOLE_LOCAL_REPO/gravity.sh"
install -o "$app" -Dm755 -t "$PI_HOLE_INSTALL_DIR" "$PI_HOLE_LOCAL_REPO/advanced/Scripts"/*.sh
install -o "$app" -Dm755 -t "$PI_HOLE_INSTALL_DIR" "$PI_HOLE_LOCAL_REPO/advanced/Scripts/COL_TABLE"
install -Dm644 -t /etc/bash_completion.d/          "$PI_HOLE_LOCAL_REPO/advanced/bash-completion/pihole"

install -o "$app" -Dm755 -t "$PI_HOLE_BIN_DIR" "$PI_HOLE_LOCAL_REPO/pihole"

#=================================================
# INSTALL THE CONFIGS
#=================================================
ynh_script_progression --message="Installing $app's configuration files..." --weight=1

install -d -m 0755 "$PI_HOLE_CONFIG_DIR"
ynh_add_config --template="dns-servers.conf" --destination="$PI_HOLE_CONFIG_DIR/dns-servers.conf"
ynh_add_config --template="pihole-FTL.conf" --destination="$PI_HOLE_CONFIG_DIR/pihole-FTL.conf"
ynh_add_config --template="setupVars.conf" --destination="$PI_HOLE_CONFIG_DIR/setupVars.conf"

chmod 644 "${PI_HOLE_CONFIG_DIR}/dns-servers.conf"

#=================================================
# SET VERSIONS FOR THE FOOTER OF THE WEB INTERFACE
#=================================================
ynh_script_progression --message="Setting versions for the footer of the web interface..." --weight=1

echo "master master master" > "$PI_HOLE_CONFIG_DIR/localbranches"
echo "$(ynh_app_upstream_version) $pihole_adminlte_version $pihole_flt_version" \
    | tee "$PI_HOLE_CONFIG_DIR/"{GitHubVersions,localversions} > /dev/null

#=================================================
# BUILD THE LISTS WITH GRAVITY
#=================================================
ynh_script_progression --message="Building the lists with Gravity..." --weight=7

ynh_add_config --template="adlists.default" --destination="$PI_HOLE_CONFIG_DIR/adlists.list"
ynh_exec_warn_less "$PI_HOLE_INSTALL_DIR/gravity.sh" --force

#=================================================
# CONFIGURE DNS FOR THE LOCAL DOMAINS
#=================================================
ynh_script_progression --message="Configuring DNS for the local domains..." --weight=7

# List all YunoHost domains
while read -r perdomain; do
    # Comment domain resolution in /etc/hosts on 127.0.0.1, because they can interfere with the local network resolution.
    ynh_replace_string --match_string="^127.0.0.1.*$perdomain" --replace_string="#Commented by pihole# &" --target_file=/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/.*: \|.*- //')"

#=================================================
# DISABLING DNSMASQ
#=================================================
ynh_script_progression --message="Disabling Dnsmasq in system and yunohost..." --weight=1

# Stop dnsmasq to replace it by pihole-FTL
ynh_systemd_action --service_name=dnsmasq --action=stop

# Replace the service dnsmasq by pihole-FTL
# That way, YunoHost can continue to use dnsmasq by actually using pihole-FTL
#ln -sf /run/systemd/generator.late/pihole-FTL.service /etc/systemd/system/dnsmasq.service
systemctl mask dnsmasq.service

# Reload systemd config
systemctl daemon-reload

# Workaround for strings to not be replaced
a_range="__A_RANGE__"
b_range="__B_RANGE__"
gateway="__GATEWAY__"
ynh_add_config --template="dnsmasq_regenconf_hook" --destination="/usr/share/yunohost/hooks/conf_regen/50-dnsmasq_$app"
ynh_exec_warn_less yunohost tools regen-conf dnsmasq

#=================================================
# SYSTEM CONFIGURATION
#=================================================
ynh_script_progression --message="Adding system configurations related to $app..." --weight=1

# Create a dedicated PHP-FPM config
ynh_add_fpm_config

# Create a dedicated NGINX config
ynh_add_nginx_config

# Create sudoers config
_add_sudoers_config

_add_cron_jobs

_add_logrotate_config

install -T -m 0755 "${PI_HOLE_LOCAL_REPO}/advanced/Templates/pihole-FTL.service" "/etc/init.d/pihole-FTL"
install -T -m 0755 "${PI_HOLE_LOCAL_REPO}/advanced/Templates/pihole-FTL-prestart.sh" "${PI_HOLE_INSTALL_DIR}/pihole-FTL-prestart.sh"
install -T -m 0755 "${PI_HOLE_LOCAL_REPO}/advanced/Templates/pihole-FTL-poststop.sh" "${PI_HOLE_INSTALL_DIR}/pihole-FTL-poststop.sh"

ynh_exec_warn_less systemctl enable pihole-FTL --quiet
yunohost service add pihole-FTL --description="PiHole backend service" --log="/var/log/pihole-FTL.log" --needs_exposed_ports 53 67

#=================================================
# START SYSTEMD SERVICE
#=================================================
ynh_script_progression --message="Starting $app's systemd service..." --weight=2

ynh_systemd_action --service_name="pihole-FTL" --action=restart --log_path="/var/log/pihole-FTL.log"

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

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