#!/bin/bash

SERIAL_GROUP=$(stat -c "%G" /dev/ttyS0 2>/dev/ttyUSB0 2>/dev/null | head -n 1)

if [ -z "$SERIAL_GROUP" ] || [ "$SERIAL_GROUP" == "root" ]; then
    if grep -q "^uucp:" /etc/group; then
        SERIAL_GROUP="uucp"
    elif grep -q "^dialout:" /etc/group; then
        SERIAL_GROUP="dialout"
    else
        SERIAL_GROUP="plugdev"
    fi
fi

echo "--- Aillio udev Permission Fix ---"
echo "Detected serial group: $SERIAL_GROUP"

TARGET_USER=${SUDO_USER:-$USER}

for GRP in "$SERIAL_GROUP" "plugdev"; do
    if grep -q "^$GRP:" /etc/group; then
        echo "Adding $TARGET_USER to $GRP..."
        sudo usermod -a -G "$GRP" "$TARGET_USER"
    fi
done

RULE_FILE="/etc/udev/rules.d/99-aillio.rules"

if [ -f "$RULE_FILE" ]; then
    echo "Removing existing rule file..."
    sudo rm "$RULE_FILE"
fi

echo "Creating udev rules at $RULE_FILE..."
sudo bash -c "cat <<EOF > $RULE_FILE
# Aillio Devices
SUBSYSTEMS==\"usb\", ATTRS{idVendor}==\"0483\", MODE=\"0666\", GROUP=\"$SERIAL_GROUP\"
EOF"

echo "Reloading udev rules..."
sudo udevadm control --reload-rules
sudo udevadm trigger

echo "--------------------------------------------------------"
echo "SUCCESS: Permissions have been updated."
echo "CRITICAL: You must LOG OUT and LOG BACK IN for groups to update."
echo "--------------------------------------------------------"
