#!/bin/sh

# exit on error
set -e

# to add libraries to the cache
ldconfig || true

# define && install defaults
PICO_MODE="0666"
PICO_VID="0ce9"
PICO_UDEV_FILE="/etc/udev/rules.d/95-pico.rules"

# loader configuration
PICO_LDCONF_D="/etc/ld.so.conf.d"
PICO_LDCONF_F="picoscope.conf"
PICO_LDCONF_P="/opt/picoscope/lib"

if [ -d "$PICO_LDCONF_D" ];
then
    if [ -e "$PICO_LDCONF_D""/""$PICO_LDCONF_F" ];
    then
	PICO_LDCONF_N=$( grep -m1 "^""$PICO_LDCONF_P""\$" "$PICO_LDCONF_D""/""$PICO_LDCONF_F" ) || true
	if [ "x""$PICO_LDCONF_N" != "x""$PICO_LDCONF_P" ];
	then
	    echo "$PICO_LDCONF_P" >> "$PICO_LDCONF_D""/""$PICO_LDCONF_F"
	fi
    else
	echo "$PICO_LDCONF_P" > "$PICO_LDCONF_D""/""$PICO_LDCONF_F"
    fi
fi

if ! command -v udevadm > /dev/null 2>&1
then
	echo "WARNING: udev system not found, manual configuration is likely to be required for device communication!" >&2
	echo "         If running in a container, ensure this package is installed on the host and devices are passed to the container." >&2
else
	# write udev rule
	echo "ATTRS{idVendor}==\"$PICO_VID\", MODE=\"$PICO_MODE\"" > $PICO_UDEV_FILE
	
	# reload udev rules (avoids user needing to manually reload rules after install,
	# although device disconnect/reconnect might still be required on some systems)
	udevadm control --reload-rules && udevadm trigger --attr-match=idVendor='0ce9'
fi

