#!/bin/bash

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

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

#=================================================
# LOAD SETTINGS
#=================================================
ynh_script_progression --message="Loading installation settings..." --weight=1

app=$YNH_APP_INSTANCE_NAME

domain=$(ynh_app_setting_get --app=$app --key=domain)
path_url=$(ynh_app_setting_get --app=$app --key=path)
port=$(ynh_app_setting_get --app=$app --key=port)
port_wg=$(ynh_app_setting_get --app=$app --key=port_wg)
final_path=$(ynh_app_setting_get --app=$app --key=final_path)
architecture=$YNH_ARCH

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

upgrade_type=$(ynh_check_app_version_changed)

#=================================================
# BACKUP BEFORE UPGRADE THEN ACTIVE TRAP
#=================================================
ynh_script_progression --message="Backing up the app before upgrading (may take a while)..." --weight=1

# Backup the current version of the app
ynh_backup_before_upgrade
ynh_clean_setup () {
	# restore it if the upgrade fails
	ynh_restore_upgradebackup
}
# Exit if an error occurs during the execution of the script
ynh_abort_if_errors

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

# If final_path doesn't exist, create it
if [ -z "$final_path" ]; then
	final_path=/opt/yunohost/$app
	ynh_app_setting_set --app=$app --key=final_path --value=$final_path
fi

# Change port if WireGuard port is the same as WireGuard UI's
if [ $port -eq $port_wg ]
then
	ynh_app_setting_delete --app=$app --key=port
	port=$(ynh_find_port --port=$(($port_wg+1)))
	ynh_app_setting_set --app=$app --key=port --value=$port
	# Let's remove the unused is_public key too
	ynh_app_setting_delete --app=$app --key=is_public
fi

# WireGuard UI should be private, really.
if ynh_permission_has_user --permission=main --user=visitors
then
        ynh_permission_update --permission=main --remove=visitors
fi

# Downgrade linux-image-$arch if updated to the buster-backports version
linuximage_version=$(ynh_package_version --package=linux-image-$architecture)
if [[ $linuximage_version == *"bpo10"* ]]
then
	# Downgrading using ynh_package_install apt command without "--no-remove" and with "--allow-downgrades"
	# It will remove wireguard-ynh-deps and wireguard but they will be reinstalled throught upgrade process
	ynh_apt --allow-downgrades --option Dpkg::Options::=--force-confdef \
        --option Dpkg::Options::=--force-confold install linux-image-$architecture/stable

	#Remove backports kernel if running on it and send a mail to the admin to ask him to reboot
	linuxkernel_version=$(uname -r)
	if [[ $linuxkernel_version == *"bpo"* ]]
	then
		ynh_package_remove linux-image-$linuxkernel_version

		echo "You've been using an experimental version of wireguard_ynh, which was using the backports version of the linux kernel.
Now wireguard_ynh use a DKMS module allowing itself to be used with the stable kernel, then the backports one was removed and a reboot is needed to go back to the stable one." > mail_to_send

		ynh_send_readme_to_admin --app_message="mail_to_send" --recipients="admin" --type=upgrade
	fi
fi

# Drop sudoers file if present
if [ -f "/etc/sudoers.d/${app}_ynh" ]; then
	ynh_secure_remove /etc/sudoers.d/${app}_ynh
fi

# Remove deprecated services
if systemctl list-units --full -all | grep -Fq "wireguard_ui_conf.path"; then
	systemctl disable --now --quiet wireguard_ui_conf.path
	ynh_secure_remove --file="/etc/systemd/system/wireguard_ui_conf.path"
fi
if systemctl list-units --full -all | grep -Fq "wireguard_ui_conf.service"; then
	systemctl disable --now --quiet wireguard_ui_conf.service
	ynh_secure_remove --file="/etc/systemd/system/wireguard_ui_conf.service"
fi

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

ynh_systemd_action --service_name=wireguard_ui --action="stop" --line_match="Stopped WireGuard UI" --log_path="systemd" --timeout=30
ynh_systemd_action --service_name=wireguard@wg0 --action="stop"

#=================================================
# 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="$final_path" --source_id="$architecture"
fi

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

# Update configuration for the Web UI
ynh_add_config --template="../conf/wireguard-ui.env" --destination="$final_path/wireguard-ui.env"

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

# Create a dedicated nginx config
ynh_add_nginx_config

#=================================================
# UPGRADE DEPENDENCIES
#=================================================
ynh_script_progression --message="Upgrading dependencies..." --weight=7

#TODO: remove buster-backports kernel

# Add buster-backports gpg key
ynh_install_repo_gpg --key="https://ftp-master.debian.org/keys/archive-key-10.asc" --name="$app"

# Add buster-backports repo
ynh_add_repo --uri="http://deb.debian.org/debian" --suite="buster-backports" --component="main" --name="$app"

# Add pin-priority for wireguard packages
ynh_pin_repo --package="wireguard*" --pin="origin deb http://deb.debian.org/debian buster-backports main" --priority=995 --name="$app"

# Update the list of package with the new repo
ynh_package_update

ynh_add_app_dependencies --package="$pkg_dependencies"

# Remove buster-backports repo and pin-priority
ynh_remove_extra_repo --name=$app

#=================================================
# CREATE DEDICATED USER
#=================================================
ynh_script_progression --message="Making sure dedicated system user exists..." --weight=1

# Create a dedicated user (if not existing)
ynh_system_user_create --username=$app

#=================================================
# SETUP SYSTEMD
#=================================================
ynh_script_progression --message="Upgrading systemd configuration..." --weight=1

# Create a dedicated systemd config for the web UI
ynh_add_systemd_config --service=wireguard_ui --template=wireguard_ui.service

# Create dedicated systemd configs for starting and monitoring WireGuard's configuration
cp ../conf/wireguard@.service /etc/systemd/system/wireguard@.service
cp ../conf/wireguard@.path /etc/systemd/system/wireguard@.path
systemctl daemon-reload
systemctl enable --quiet wireguard@wg0.service
systemctl enable --quiet --now wireguard@wg0.path

#=================================================
# ENABLE PORT FORWARDING
#=================================================
ynh_script_progression --message="Enabling port forwarding..." --weight=1

ynh_add_config --template="../conf/sysctl.conf" --destination="/etc/sysctl.d/$app.conf"
sysctl -p /etc/sysctl.d/$app.conf

#=================================================
# GENERIC FINALIZATION
#=================================================
# SECURE FILES AND DIRECTORIES
#=================================================

# Set permissions to app files
chmod 750 "$final_path"
chmod -R o-rwx "$final_path"
chown -R $app: "$final_path"

chmod 750 /etc/wireguard
chmod -R o-rwx /etc/wireguard
chown -R $app: /etc/wireguard

#=================================================
# INTEGRATE SERVICE IN YUNOHOST
#=================================================
ynh_script_progression --message="Integrating service in YunoHost..." --weight=1

yunohost service add wireguard@wg0 --description="WireGuard VPN" --needs_exposed_ports="$port_wg" --test_status="wg show | grep wg0"
yunohost service add wireguard_ui --description="WireGuard UI"

#=================================================
# START SYSTEMD SERVICE
#=================================================
ynh_script_progression --message="Starting the systemd service for the UI..." --weight=1

# Start a systemd service
ynh_systemd_action --service_name=wireguard_ui --action="start" --line_match="http server started" --log_path="systemd" --timeout=30

#=================================================
# RELOAD NGINX
#=================================================
ynh_script_progression --message="Reloading nginx web server..." --weight=1

ynh_systemd_action --service_name=nginx --action=reload

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

ynh_script_progression --message="Upgrade of $app completed. You may need to reboot your server before being able to start the WireGuard service." --last