#!/bin/bash
set -e
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

BINARY="/usr/local/bin/e710_reader"
DEFAULTS="/etc/default/e710-rfid"
SERVICE="/etc/systemd/system/e710-rfid.service"

echo "[INSTALL] Stopping existing service (if any)..."
if systemctl is-active --quiet e710-rfid 2>/dev/null; then
    systemctl stop e710-rfid || true
fi

echo "[INSTALL] Installing binary..."
cp "${DIR}/e710_reader" "${BINARY}"
chmod +x "${BINARY}"

echo "[INSTALL] Installing config..."
cp "${DIR}/e710-rfid.default" "${DEFAULTS}"

echo "[INSTALL] Installing service..."
cp "${DIR}/e710-rfid.service" "${SERVICE}"

if command -v systemctl >/dev/null 2>&1; then
    echo "[INSTALL] Reloading systemd..."
    systemctl daemon-reload
    echo "[INSTALL] Enabling and starting service..."
    systemctl enable e710-rfid
    systemctl start e710-rfid
    echo ""
    echo "[INSTALL] Done. Service status:"
    systemctl status e710-rfid --no-pager || true
else
    echo "[INSTALL] systemd not found. Skipping service start."
    echo "[INSTALL] You can start the binary manually:"
    echo "  ${BINARY} \$(cat ${DEFAULTS} | grep E710_ARGS | cut -d= -f2-)"
fi
