#!/bin/bash

file="lazer.wav"

download()
{
	echo "Downloading $1"
	if which curl &>/dev/null; then
		curl "$1" > "$2"
	elif which wget &>/dev/null; then
		wget "$1" -O "$2"
	else
		echo "You need either wget or curl."
		exit 1
	fi
	echo "Download complete."
}

getkbds()
{
	xinput list | grep -i keyboard | grep -vi virtual | sed 's/.*id=//' | cut -f1
}

getevents()
{
	while :; do
		xinput test "$1"
		sleep 1
	done
}

playsound()
{
	script="print(max(($1 % 64) / 32, 0.5))"
	pitch=$(python -c "$script")

	mplayer \
		-af scaletempo=scale=1.0:speed=both \
		-speed "$pitch" \
		"$file" &> /dev/null
}

curtime()
{
	date +%s%3N | tail -c 8
}

nextpress=0
keypressed()
{
	if [ $(curtime) -gt "$nextpress" ]; then
		playsound $(sed 's/key press\s*//' <<< "$1") &
		nextpress=$(expr $(curtime) '+' '50')
	fi
}

synther()
{
	getevents "$1" \
		| grep --line-buffered -i "key press" \
		| while read -r line; do keypressed "$line"; done
}

for i in $(getkbds); do
	synther "$i" &
done

onterm()
{
	pkill -TERM -P $$
	exit $1
}

trap onterm SIGINT
trap onterm SIGTERM

if [ ! -f "$file" ]; then
	download "https://s.mort.coffee/d/file/$file" "$file"
fi

while :; do sleep 1; done
