#!/bin/sh

. /etc/control.d/functions

CONFIG=/etc/pam.d/xrdp-sesman

new_help enabled 'Enable attach redirected USB devices in RDP session'
new_help disabled 'Disable attach redirected USB devices in RDP session'

new_summary 'Attach redirected USB devices in RDP session'

get_status()
{
	local STATUS=unknown
	grep -Pq '(?!usbip-attach)' $CONFIG && STATUS=disabled
	grep -q '^-\?account[[:space:]]\+optional[[:space:]]\+pam_exec.so.*/usr/sbin/usbip-attach' $CONFIG && STATUS=enabled
        echo "$STATUS"	
}

REQUEST="$*"

case "$REQUEST" in
        help|'help '*)
                control_help "${REQUEST#help}"
                ;;
        list)
                control_list
                ;;
        summary)
                control_summary
                ;;
        status|'')
                get_status
                ;;
	enabled|disabled)
		CURRENT="$(get_status)"
                if [ "$REQUEST" != "$CURRENT" ]; then
                        case "$REQUEST" in
				enabled)
					echo "account         optional        pam_exec.so /usr/sbin/usbip-attach" >> $CONFIG
					;;
				disabled)
					subst '/^-\?account[[:space:]]\+optional[[:space:]]\+pam_exec.so.*\/usr\/sbin\/usbip-attach/d' $CONFIG
					;;
			esac
		fi
                ;;
        *)
                printf '%s: %s\n' "${0##*/}" "Invalid mode: $REQUEST" >&2
                exit 1
esac

