#!/usr/bin/env bash

trap "echo Exited!; exit;" SIGINT SIGTERM

OLD="$(lsusb)"
while true; do
    watch --chgexit -n0.2 lsusb >& /dev/null
    NEW="$(lsusb)"

    diff <(cat <<<"$OLD") <(cat <<<"$NEW") --unified | grep '^[+-]' | grep -Ev '^(---|\+\+\+)' |
    while read line; do
        echo "$line"
        ID="$(   echo "$line" | cut -c2- | cut -d' ' -f-6 )"
        LABEL="$(echo "$line" | cut -c2- | cut -d' ' -f7- )"
        case "$line" in
            \+*)
                notify-send --icon=device --expire-time=500 "New device connected" "${LABEL} <i>($ID)</i>"
            ;;
            \-*)
                notify-send --icon=device --expire-time=500 "Device disconnected" "${LABEL} <i>($ID)</i>"
            ;;
        esac
    done

    OLD="$NEW"
done
