#!/bin/bash
SERVICE_NAME="esn-holter"
if [ -n "$SUDO_USER" ]; then
	PATH_HOME=$(getent passwd "$SUDO_USER" | cut -d: -f6)
else
	PATH_HOME="$HOME"
fi
USERNAME=$(basename "$PATH_HOME")
SERVICE_DIR="$PATH_HOME/.config/systemd/user"
SERVICE_FILE="$SERVICE_DIR/$SERVICE_NAME.service"
RULES_PATH="/etc/udev/rules.d/myftdi.rules"

if [ -n "$SUDO_USER" ]; then
    USER_ID=$(id -u "$SUDO_USER")
    export XDG_RUNTIME_DIR="/run/user/$USER_ID"
    export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus"
	
	sudo -u "$SUDO_USER" XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" DBUS_SESSION_BUS_ADDRESS="$DBUS_SESSION_BUS_ADDRESS" systemctl --user stop "$SERVICE_NAME.service"
	sudo -u "$SUDO_USER" XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" DBUS_SESSION_BUS_ADDRESS="$DBUS_SESSION_BUS_ADDRESS" systemctl --user disable "$SERVICE_NAME.service"
	rm -f "$SERVICE_FILE"
	sudo -u "$SUDO_USER" XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" DBUS_SESSION_BUS_ADDRESS="$DBUS_SESSION_BUS_ADDRESS" systemctl --user daemon-reload
else
	systemctl --user stop "$SERVICE_NAME.service"
	systemctl --user disable "$SERVICE_NAME.service"
	rm -f "$SERVICE_FILE"
	systemctl --user daemon-reload
fi

sudo rm -f "$RULES_PATH"
sudo rm -f /etc/sudoers.d/"$USERNAME"-trigger
sudo udevadm control --reload-rules
sudo udevadm trigger

rm -f "/tmp/uninstall_ESNHolter_service.sh"