#!/bin/bash
# Init joypads, if present
# 23/01/2017
# Daniele Callari
# www.daxtech.net


xboxdrv --quiet --silent --detach-kernel-driver &
sleep 1

killall xboxdrv
sleep 1

LED=1
xboxdrv -L | grep "0x" | while read -r line ; do

	if [[ $line == *"PLAYSTATION"* ]]; then

		ID=$(echo $line | grep -o -E '[0-9]+' | head -1 | sed -e 's/^\+//')
	        LED=`expr $LED + 1`

                xboxdrv \
                --id $ID \
                --led $LED \
                --mimic-xpad \
                --dbus disabled \
                --dpad-rotation 90 \
                --axismap -DPAD_X=DPAD_X \
                --buttonmap Y=X \
                --buttonmap X=Y \
		--silent \
		--quiet &

	        printf  "\e[92mPlayStation pad $ID $LED has been initialized\e[39m\n"

	elif [[ $line == *"Xbox 360"* ]]; then

		ID=$(echo $line | grep -o -E '[0-9]+' | head -1 | sed -e 's/^\+//')
	        LED=`expr $LED + 1`

		xboxdrv \
	        --id $ID \
        	--trigger-as-button \
        	--led $LED \
        	--deadzone 4000 \
        	--dpad-rotation 90 \
        	--axismap -DPAD_X=DPAD_X \
        	--buttonmap Y=X \
        	--buttonmap X=Y \
        	--silent \
        	--quiet \
        	--mimic-xpad \
        	--dbus disabled &

	        printf  "\e[92mxBox pad $ID $LED has been initialized\e[39m\n"

	fi

	sleep 2
done
