#!/usr/bin/env bash

function help()
{
cat << EOF
Usage: devinput.sh [-i]  [input.h path] > outfile

devinput.sh parses a linux input.h header file and produces a
lircd.conf file for the devinput driver tailored for the local
system. Using the -i option, it produces an internal format
used when building lirc.

input.h path defaults to /usr/include/linux/input.h, often in
the kernel-headers package.

Script uses the python interpreter defined by the PYTHON
environment variable, falling back to 'python'
EOF
}

here=$(dirname $(${PYTHON:-'python'} -c "import os; print(os.path.realpath(\"$0\"))"))

# Use gnu-sed if available
if which gsed &>/dev/null; then SED=gsed; else SED=sed; fi

lirc_map=''

if [[ "$1" = '-h' || "$1" = '--help' ]]; then
    help
    exit 0
elif [[ "$1" = -i ]]; then
    lirc_map="true"
    shift
fi

readonly TYPES="KEY BTN"
if test -e "/usr/include/linux/input-event-codes.h"; then
readonly file=${1:-/usr/include/linux/input-event-codes.h}
elif test -e "/usr/include/linux/input.h"; then
readonly file=${1:-/usr/include/linux/input.h}
elif test -e "$here/../include/linux/input-event-codes.h"; then
readonly file=${1:-$here/../include/linux/input-event-codes.h}
fi
tmpfile=$( mktemp "${TMPDIR:-/tmp}/devinput.XXXXXXXXX" )

if ! test -f $file; then
    echo "Cannot access $file. Giving up" >&2
    exit 1
fi

for type in $TYPES; do
    grep "^#define ${type}_" < $file | \
    sort | \
    $SED -ne "s/^#define \([^ \t]*\)[ \t][ \t]*\([0-9][0-9a-fA-FxX]*\).*/{\"\1\", \2},/p"
done > $tmpfile

if test -n "$lirc_map"; then
    cat $tmpfile
    rm -f $tmpfile
    exit 0
fi


echo "# Generated by $(basename $0) on $(uname -r)"
echo "# Date: $(date)"
cat <<EOF

begin remote
        name            devinput-64
        bits            16
        eps             30
        aeps            100
        pre_data_bits   16
        pre_data        0x0001
        post_data_bits  32
        post_data       0x00000001
        gap             132799
        toggle_bit      0
	driver          devinput

        begin codes
EOF

sed "s/^{\"\([^\"]*\)\", \(.*\)},/         \1      \2/" <$tmpfile
cat <<EOF
        end codes
end remote
EOF

echo
echo "# generated by $(basename $0) (obsolete 32 bit version)"
cat <<EOF

begin remote
        name            devinput-32
        bits            16
        eps             30
        aeps            100
        pre_data_bits   16
        pre_data        0x8001
        gap             132799
        toggle_bit      0
        driver          devinput

        begin codes
EOF

sed "s/^{\"\([^\"]*\)\", \(.*\)},/         \1      \2/" < $tmpfile
cat <<EOF
        end codes
end remote
EOF

rm -f $tmpfile
