#!/bin/sh
# tlp - handle added usb devices
#
# Copyright (c) 2024 Thomas Koch <linrunner at gmx.net> and others.
# SPDX-License-Identifier: GPL-2.0-or-later
#
# Remark: the calling udev rule is triggered for "base" devices only,
#         not for the corresponding subdevices.

# --- Source libraries

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

# --- MAIN
# shellcheck disable=SC2034
_bgtask=1

# read configuration: quit on error, trace allowed
read_config 1 0

# quit if TLP disabled
check_tlp_enabled || do_exit 0

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

case "$1" in
    usb) # usb devices in general
        [ "$USB_AUTOSUSPEND" = "1" ] || do_exit 0
        # quit if usb autosuspend disabled

        # 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

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


        # handle device
        usb_suspend_device "/sys$2" "udev"
        ;;

    disk) # (s)ata disks attached via usb
        get_power_mode; pwrmode=$?
        dev="${2##*/block/}"
        set_ahci_disk_runtime_pm $pwrmode "$dev"
        set_disk_apm_level $pwrmode "$dev"
        set_disk_spindown_timeout $pwrmode "$dev"
        set_disk_iosched "$dev"
        ;;
esac

do_exit 0
