#!/usr/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 | grep -Po '(created|reconnected).*ip \K[^\s]*' | sed 's/\(.*\):/\1 /;s/::ffff://' | awk '{ print $1 }' | 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-].*[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
