#!/bin/bash
SERVICE_NAME="esn-holter"
JAR_FILE="ESNHolterServer.jar"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTALL_DIR="$(dirname "$SCRIPT_DIR")"
JAR_PATH="$INSTALL_DIR/ESNHolterServer/$JAR_FILE"
if [ -n "$SUDO_USER" ]; then
	PATH_HOME=$(getent passwd "$SUDO_USER" | cut -d: -f6)
else
	PATH_HOME="$HOME"
fi
USER_NAME=$(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"

mkdir -p "$SERVICE_DIR"

cat > "$SERVICE_FILE" <<EOL
[Unit]
Description=ESN Holter Server
After=network.target
Wants=network.target

[Service]
Type=simple
ExecStart=/usr/bin/java -jar $JAR_PATH
Restart=always

[Install]
WantedBy=default.target
EOL

sudo chmod 644 "$SERVICE_FILE"

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 daemon-reload
    sudo -u "$SUDO_USER" XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" DBUS_SESSION_BUS_ADDRESS="$DBUS_SESSION_BUS_ADDRESS" systemctl --user enable "$SERVICE_NAME.service"
    sudo -u "$SUDO_USER" XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" DBUS_SESSION_BUS_ADDRESS="$DBUS_SESSION_BUS_ADDRESS" systemctl --user start "$SERVICE_NAME.service"
else
	systemctl --user daemon-reload
	systemctl --user enable "$SERVICE_NAME.service"
	systemctl --user start "$SERVICE_NAME.service"
fi

sudo tee "$RULES_PATH" > /dev/null <<EOL
SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", ACTION=="add", MODE="0666", RUN+="$INSTALL_DIR/Scripts/unbind_cm.sh"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6010", ACTION=="add", MODE="0666", RUN+="$INSTALL_DIR/Scripts/unbind_cm.sh"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6014", ACTION=="add", MODE="0666", RUN+="$INSTALL_DIR/Scripts/unbind_cm.sh"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6015", ACTION=="add", MODE="0666", RUN+="$INSTALL_DIR/Scripts/unbind_cm.sh"
EOL

sudo chmod 644 "$RULES_PATH"

sudo chown root:root "$SCRIPT_DIR/trigger_usb_rules.sh"
echo "$USER_NAME ALL=(ALL) NOPASSWD: $SCRIPT_DIR/trigger_usb_rules.sh" | sudo tee /etc/sudoers.d/"$USER_NAME"-trigger > /dev/null
sudo chmod 440 /etc/sudoers.d/"$USER_NAME"-trigger


sudo systemctl restart systemd-udevd
sudo udevadm control --reload-rules
sudo udevadm trigger --type=subsystems --subsystem-match=usb --action=add

