#!/bin/sh

. /lib/functions.sh

[ "$SUBSYSTEM" = "tty" ] || exit 0

add() {
	local cfg="$1"
	local product serial symlink usbif

	[ -c "/dev/$DEVICENAME" ] || return

	config_get product "$cfg" product
	config_get serial "$cfg" serial
	config_get symlink "$cfg" symlink
	config_get usbif "$cfg" usbif

	[ -z "$product" -a -z "$serial" -a -z "$usbif" ] && return

	. "/sys/$DEVPATH/device/../uevent"
	SERIAL="$(cat /sys/$DEVPATH/device/../../serial)" 2>/dev/null
	USBIF="$(echo $DEVPATH | awk -F/ 'BEGIN {i=3}; /ACM/ {i=2}; END {print $(NF-i)}')"

	[ -n "$product" -a "$product" != "$PRODUCT" ] && return
	[ -n "$serial" -a "$serial" != "$SERIAL" ] && return
	[ -n "$usbif" -a "$usbif" != "$USBIF" ] && return

	chgrp domoticz "/dev/$DEVICENAME"
	chmod g+rw "/dev/$DEVICENAME"

	[ -n "$symlink" ] && ln -sf "/dev/$DEVICENAME" "/dev/$symlink"
}

remove() {
	local cfg="$1"
	local symlink

	config_get symlink "$cfg" symlink

	[ "/dev/$DEVICENAME" = "$(readlink /dev/$symlink)" ] && rm "/dev/$symlink"
}

config_load "domoticz"
config_foreach "$ACTION" device
