#!/bin/sh
# tlp - handle added usb devices
#
# Copyright (c) 2019 Thomas Koch <linrunner at gmx.net> and others.
# This software is licensed under the GPL v2 or later.

# Remark: the calling udev rule is triggered for "base" devices only,
#         not for the corresponding subdevices.

# shellcheck disable=SC2086

# --- Source libraries

for lib in /usr/share/tlp/tlp-func-base /usr/share/tlp/func.d/20-tlp-func-usb; do
    # shellcheck disable=SC1090
    . $lib || exit 70
done

# --- MAIN

# read config
read_defaults

# exit if TLP or autosuspend disabled
: ${USB_AUTOSUSPEND:=${DEFAULT_USB_AUTOSUSPEND}}
check_tlp_enabled 0 && [ "$USB_AUTOSUSPEND" = "1" ] || exit 0

# USB autosuspend has two principal operation modes:
#
# Mode 1 (optional):
# - System startup is handled by tlp-functions:set_usb_suspend()
# - Startup completion is signaled by "flag file" $USB_DONE
# - Newly added devices are handled by this udev script
# - Mode 1 is enabled by the private config variable X_TLP_USB_MODE=1
#
# Mode 2 (default):
# - Everything - including system startup, but not shutdown - is handled by this udev script

# do exit if mode 1 and no startup completion flag
[ "$X_TLP_USB_MODE" = "1" ] && ! check_run_flag $USB_DONE && exit 0

if [ "$X_USB_ENV_TRACE" = "1" ]; then
    echo_debug "usb" "tlp_usb_udev.env = $(printenv)"
fi

# handle device
usb_suspend_device "/sys$1" "udev"

exit 0
