#!/bin/sh

VAR_DIR="${SYNOPKG_PKGDEST}/var"
LOG_DIR="${VAR_DIR}/logs"
LOG_FILE="${LOG_DIR}/${SYNOPKG_PKGNAME}.log"
BIN_DIR="${SYNOPKG_PKGDEST}/bin"
HOTPLUG_DIR="/usr/syno/hotplug.d/default"
HOTPLUG_FILE="usb_serial.hotplug"
UDEV_RULE_LIB="/lib/udev/rules.d"
UDEV_RULE_FILE="50-usbtty.rules"

if [ ${SYNOPKG_DSM_VERSION_MAJOR} -gt 5 ] || [ ${SYNOPKG_DSM_VERSION_MAJOR} == 5 -a ${SYNOPKG_DSM_VERSION_MINOR} -ge 1 ]; then
  USE_UDEV=1
else
  USE_UDEV=0
fi

UNINST=`lsmod | grep '^cp210x\|^ftdi_sio\|^pl2303\|^ch341' | awk '{ sum += $3 } END { print sum }'`

if [ -z ${UNINST} ] || [ ${UNINST} == 0 ]; then
    ${BIN_DIR}/${SYNOPKG_PKGNAME}.sh stop
    if [ ${USE_UDEV} == 1 ]; then
      rm ${UDEV_RULE_LIB}/${UDEV_RULE_FILE}
      udevadm control --reload-rules
    else
      rm ${HOTPLUG_DIR}/${HOTPLUG_FILE}
    fi
    rm /volume1/startup/S01loadUsbModules.sh
    exit $?
else
    echo "Can't uninstall USB Serial Drivers. Some application is currently using them. Please stop the application and then uninstall the drivers." > ${SYNOPKG_TEMP_LOGFILE}
    exit 1
fi
