#!/usr/bin/env bash

# Linux USB Serial Low Latency Setup Script
PORT="${1:-/dev/ttyUSB0}"

if [ ! -e "$PORT" ]; then
    echo "[오류] 포트 $PORT 가 존재하지 않습니다."
    exit 1
fi

DEV_NAME=$(basename "$PORT")
LATENCY_PATH="/sys/bus/usb-serial/devices/$DEV_NAME/latency_timer"

if [ -f "$LATENCY_PATH" ]; then
    OLD_VAL=$(cat "$LATENCY_PATH")
    echo "$OLD_VAL" | sudo tee "$LATENCY_PATH" > /dev/null 2>&1 || echo 1 | sudo tee "$LATENCY_PATH"
    NEW_VAL=$(cat "$LATENCY_PATH")
    echo "[성공] USB 시리얼 포트 $PORT 지연 타이머 변경: ${OLD_VAL}ms -> ${NEW_VAL}ms"
else
    # setserial fallback
    setserial "$PORT" low_latency 2>/dev/null || true
    echo "[정보] setserial low_latency 명령을 적용했습니다."
fi
