#!/bin/bash

if [[ $# -ne 1 ]]; then
	echo "Usage: $0 <pad device id>"
	exit 1
fi

ID=$1
NAME=$(xsetwacom list | grep "id: $ID" | awk 'BEGIN {FS="[a-z]+: "} {gsub(/[ \t]+$/,"",$1); print $1}')
TYPE=$(xsetwacom list | grep "id: $ID" | awk 'BEGIN {FS="[a-z]+: "} {gsub(/[ \t]+$/,"",$3); print $3}')

if [[ "$NAME" == "" ]]; then
	echo "No wacom device with id '${ID}' known."
	exit 2
elif [[ "$TYPE" != "PAD" ]]; then
	echo "'${NAME}' is not a wacom pad device (${TYPE})."
	exit 3
fi

echo "Overriding default mapping..."
for B in {1..9}; do
	xsetwacom set $ID button $B key $B 2> /dev/null
done

N=1
MAP=()
while true; do
	echo "Press button ${N} on ${NAME} or 'q' when finished"
	read -s -n 1 X > /dev/null
	if [[ "$X" == 'q' ]]; then
		break
	fi
	MAP[$N]=$X
	N=$(($N+1))
done

echo
echo "Setting up a GNOME-compatible mapping with the following commands..."
for B in ${!MAP[*]}; do
	echo "xsetwacom set $ID button ${MAP[$B]} button +${B}"
	xsetwacom set $ID button ${MAP[$B]} button +${B}
done
