#!/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"
SERVICE_DIR="$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

systemctl --user daemon-reload
systemctl --user enable "$SERVICE_NAME.service"
systemctl --user start "$SERVICE_NAME.service"

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 udevadm control --reload-rules
sudo udevadm trigger

