#!/usr/bin/env bash

for i in "$@"; do
  case $i in
    -g|--group)
      GROUP=dialout
      shift # past argument with no value
      ;;
    -g=*|--group=*)
      GROUP="${i#*=}"
      shift # past argument=value
      ;;
    -h|--help)
      echo "This script writes a udev rule for Acroname devices"
      echo "  By default, Acroname devices will be set to file mode 0666"
      echo "  Supply -g or --group to set file mode to 0660 and group to dialout"
      echo "  Supply -g=<groupname> or --group=<groupname> to set file mode to 0660 and group to <groupname>"
      exit 0
      ;;
    -*)
      echo "Unknown option $i"
      exit 1
      ;;
    *)
      ;;
  esac
done

if [ -n "$SUDO_USER" ]; then
    UN=$SUDO_USER
else
    UN=$USER
fi

REBOOT_REQUIRED=no

# Previous instances of the udev script don't work as expected on some distributions.
# So try and remove it from the list of active rules:
if test -f /etc/udev/rules.d/100-brainstem.rules; then
    sudo mv /etc/udev/rules.d/100-brainstem.rules /etc/udev/rules.d/100-brainstem.rules.deactivated
fi

echo "This script adds a udev rule to automatically setup Acroname devices:"
echo -n "  file mode to "
if [ -z "$GROUP" ]; then
    MODE="0666"
    echo "$MODE"
else
    MODE="0660"
    GROUP_STRING="GROUP=\"$GROUP\","
    echo "$MODE"
    echo "  file group to $GROUP"
    if groups "$UN" | grep -q "\b${GROUP}\b"; then
        echo "User $UN is already in group $GROUP"
    else
        echo "User $UN will be added to group $GROUP"
        REBOOT_REQUIRED=yes
        sudo usermod -a -G "$GROUP" "$UN" || exit 1
    fi
fi

cat <<EOF | sudo tee /etc/udev/rules.d/99-brainstem.rules > /dev/null
# generated by ${0##*/}

# Acroname Brainstem control devices
SUBSYSTEM=="usb",ATTRS{idVendor}=="24ff",${GROUP_STRING}MODE="$MODE"

# Acroname recovery devices (pb82, pb242, pb167)
SUBSYSTEM=="tty",ATTRS{idVendor}=="0424",ATTRS{idProduct}=="274e",${GROUP_STRING}MODE="$MODE"
SUBSYSTEM=="tty",ATTRS{idVendor}=="10c4",ATTRS{idProduct}=="ea60",${GROUP_STRING}MODE="$MODE"
KERNEL=="hidraw*",ATTRS{idVendor}=="1fc9",ATTRS{idProduct}=="0130",${GROUP_STRING}MODE="$MODE"
EOF

sudo udevadm control --reload-rules

echo -n "udev rule written. For changes to take effect, "
if [ "$REBOOT_REQUIRED" = "yes" ]; then
    echo "either reboot or completely logout and login on $UN."
else
    echo "disconnect and reconnect all Acroname devices."
fi
