#!/bin/bash

#usage: touch-on-point [endurance] XCOORDxYCORD...

endurance=5

if test $# -lt 1; then
    die "usage: touch-on-point [endurance] XCOORDxYCORD..."
fi

if echo "$1" | grep -q x; then
    true #do nothing
else
    endurance=$1
    shift
fi

if test $# -lt 1; then
    die "usage: touch-on-point [endurance] XCOORDxYCORD..."
fi

function lcd-clear() {
    echo 255 > $lcd_backlight
    set-fb-color "$@" >/dev/null 2>&1
}

lcd-clear 0 0 0 >/dev/null 2>&1 

function lcd-set-color() {
    export RED=${1:-0}
    export GREEN=${2:-0}
    export BLUE=${3:-0}
}

function lcd-vline() {
    set-fb-color $RED $GREEN $BLUE vline $1 $2 $3 >/dev/null 2>&1
}

function lcd-hline() {
    set-fb-color $RED $GREEN $BLUE hline $1 $2 $3 >/dev/null 2>&1 
}

for p in "$@"; do
    x=$(echo "$p" | sed -e 's/x.*//')
    y=$(echo "$p" | sed -e 's/.*x//')
    lcd-set-color 255 0 0
    lcd-vline $x $y $endurance
    lcd-hline $x $y $endurance
    touch_p=$(tcmd-subcase.sh touch-get-point | head -n 1 | sed -e 's/.*(//; s/).*//')
    touch_x=$(echo "$touch_p" | sed -e 's/x.*//')
    touch_y=$(echo "$touch_p" | sed -e 's/.*x//')

    diff_x=$(( touch_x - x ))
    diff_y=$(( touch_y - y ))
    diff_x=$((diff_x < 0 ? -diff_x : diff_x))
    diff_y=$((diff_y < 0 ? -diff_y : diff_y))

    if (( diff_x < endurance && diff_y < endurance)); then
	echo "OK, touch ${touch_x}x${touch_y} is good for ${x}x${y}"
    else
	die "OK, touch ${touch_x}x${touch_y} is bad for ${x}x${y}"
    fi
done
