#!/bin/sh

# Copyright 2021 by Andrey Cherepanov (cas@altlinux.org)

# This program is free software; you can redistribute it and/or modify it
# under the terms of GNU General Public License (GPL) version 3 or later.

log_file="/var/log/usbip-attach"
usbip_program="/usr/sbin/usbip"
host="$(journalctl -u xrdp-sesman | sed -n 's/^.*++ \(created\|reconnected\).* ip \([0-9.]*\):.*$/\2/p' | tail -1)"

echo "$(date) Connected from $host" >> $log_file
$usbip_program list -r "$host" 2>&1 >> $log_file
$usbip_program list -r "$host" 2>/dev/null | sed -n 's/^ *\([0-9-]\+\):.*$/\1/p' | while read id;do
	echo "Found exported USB device $id, try to attach..." >> $log_file
	$usbip_program attach -r "$host" -b "$id" 2>&1 >> $log_file
done
