#!/bin/sh
# Copyright (c) 2016 DisplayLink (UK) Ltd.
# File autogenerated by udev-installer.sh script

get_evdi_dev_count()
{
  if [ "$(ls -l /sys/devices/platform/* | grep evdi | wc -l)" = "0" ]; then
    echo "0"
    return
  fi

  cat /sys/devices/platform/evdi.*/drm/card*/card*/status | grep "^connected$" | wc -l
}

get_displaylink_dev_count()
{
  cat /sys/bus/usb/devices/*/idVendor | grep 17e9 | wc -l
}

start_displaylink()
{
  if [ "$(get_displaylink_dev_count)" != "0" ]; then
    start_service
  fi
}

try_stop_displaylink()
{
  if [ "$(get_evdi_dev_count)" = "0" ]; then
    parent_dev_path="$1"
    if [ -d "$parent_dev_path" ]; then
      echo "1"
      return
    fi

    if [ "$(get_displaylink_dev_count)" = "0" ]; then
      stop_service
      echo "0"
      return
    fi
  fi
  echo "1"
}

stop_displaylink()
{
  parent_devpath=$(dirname /sys$1)
  retry_num="50" # 5s
  while [ "$(try_stop_displaylink $parent_devpath)" != "0" ] && [ "$retry_num" != "0" ];
  do
    sleep 0.1
    retry_num=$((retry_num-1))
  done
}

main()
{
  op=$1
  devpath=$2
  if [ "$op" = "START" ]; then
    start_displaylink
  elif [ "$op" = "STOP" ]; then
    stop_displaylink $devpath
  fi
}

start_service()
{
  sh /etc/rc.d/rc.displaylink start &
}

stop_service()
{
  sh /etc/rc.d/rc.displaylink stop &
}


main $1 $2
