#!/bin/bash
# Install udev rules for Proxmark3 device detection
# Run with sudo

set -e

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
UDEV_RULES_SRC="$PROJECT_ROOT/udev/77-dangerous-pi-pm3.rules"
UDEV_RULES_DEST="/etc/udev/rules.d/77-dangerous-pi-pm3.rules"

echo "Installing Proxmark3 udev rules for Dangerous Pi..."

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "ERROR: This script must be run as root (use sudo)"
    exit 1
fi

# Check if source file exists
if [ ! -f "$UDEV_RULES_SRC" ]; then
    echo "ERROR: Source udev rules file not found: $UDEV_RULES_SRC"
    exit 1
fi

# Copy rules file
echo "Copying udev rules to $UDEV_RULES_DEST..."
cp "$UDEV_RULES_SRC" "$UDEV_RULES_DEST"
chmod 644 "$UDEV_RULES_DEST"

# Reload udev rules
echo "Reloading udev rules..."
udevadm control --reload-rules
udevadm trigger

# Add user to plugdev group if not already a member
if ! groups $SUDO_USER | grep -q '\bplugdev\b'; then
    echo "Adding user $SUDO_USER to plugdev group..."
    usermod -a -G plugdev $SUDO_USER
    echo "NOTE: User must log out and back in for group membership to take effect"
fi

echo ""
echo "✓ Udev rules installed successfully!"
echo ""
echo "The following rules are now active:"
echo "  - Proxmark3 RDV4/Easy devices will be accessible at /dev/ttyACM*"
echo "  - Devices will have permissions 0666 (readable/writable by all)"
echo "  - Symlinks created: /dev/proxmark3-*"
echo "  - Events logged to system logger"
echo ""
echo "To test, connect a Proxmark3 device and run:"
echo "  ls -l /dev/ttyACM*"
echo "  ls -l /dev/proxmark3-*"
echo ""
