#!/bin/bash

#
# Extract a sysinfo archive into a directory suitable for commit and
# auto-generate a tablet definition file.
#
# Usage: 
#     git-update.sh <sysinfo-dir> --ref=<info> --oem=<name> --product=<name>
#
# sysinfo-dir       Path to the sysinfo directory to be processed
# --ref=<post>      Link to the post containing the sysinfo, or other reference
# --oem=<name>      OEM name
# --product=<name>  Product name
#

set -e

SCRIPTDIR=$(dirname $(readlink -f "$0"))

####################
# Argument parsing
#
for arg in "${@}"; do
  case $arg in
    --ref=*) REF="${arg#*=}"; shift;;
    --oem=*) OEM="${arg#*=}"; shift;;
    --product=*) PRODUCT="${arg#*=}"; shift;;
    *) WORKDIR=$(readlink -f "${arg}"); shift;;
  esac
done

if [[ -z "${REF}" ]]; then
  echo "ERROR: The --ref=<issue> parameter is required."
  exit 1
fi
if [[ -z "${OEM}" ]]; then
  echo "ERROR: The --oem=<name> parameter is required."
  exit 1
fi
if [[ -z "${PRODUCT}" ]]; then
  echo "ERROR: The --product=<name> parameter is required."
  exit 1
fi

####################
# Determine libwacom properties
#

cd "${WORKDIR}"
IDENT=$(basename "$(readlink -f .)")

if test $(ls *.hid.txt 2>/dev/null | wc -l) -eq 0; then
  echo "ERROR: No converted HID data found. Was the sensor detected?"
  exit 1
fi

PEN_FILE=$(grep -l "Usage (Pen)" *.hid.txt || true)
TOUCHSCREEN_FILE=$(grep -l "Usage (Touchscreen)" *.hid.txt || true)

SKIP=0
if [[ $(wc -l <<< "${PEN_FILE}") -eq 0 ]]; then
    echo "WARNING: No pen devices found."
    SKIP=1
fi
if [[ $(wc -l <<< "${PEN_FILE}") -gt 1 ]]; then
    echo "WARNING: Multiple pen devices found."
    SKIP=1
fi
if [[ $(wc -l <<< "${TOUCHSCREEN_FILE}") -gt 1 ]]; then
    echo "WARNING: Multiple touchscreens found."
    SKIP=1
fi
if [[ "${PEN_FILE}" != *:056A:* && "${PEN_FILE}" != *:2D1F:* ]]; then
    echo "NOTE: Pen device is not a Wacom sensor. Tablet definition cannot be auto-generated."
    SKIP=1
fi

if [[ ${SKIP} -ne 0 ]]; then
    echo "NOTE: Unable to parse HID data. Skipping creation of libwacom tablet definition."
    exit 0
else
    echo "Attempting to parse HID data and create libwacom tablet definition..."
fi

PEN_ID=$(cut -d. -f1 <<< "${PEN_FILE}" | sed 's/^0003/usb/; s/^0018/i2c/' | tr 'A-F' 'a-f' | tr ':' '|')
PEN_VID=$(cut -d\| -f2 <<< "${PEN_ID}")
PEN_PID=$(cut -d\| -f3 <<< "${PEN_ID}")
TOUCHSCREEN_ID=$(cut -d. -f1 <<< "${TOUCHSCREEN_FILE}" | sed 's/^0003/usb/; s/^0018/i2c/' | tr 'A-F' 'a-f' | tr ':' '|')
TOUCHSCREEN_VID=$(cut -d: -f2 <<< "${TOUCHSCREEN_ID}")
TOUCHSCREEN_PID=$(cut -d: -f3 <<< "${TOUCHSCREEN_ID}")

PEN_DATA=$(awk -f ${SCRIPTDIR}/hid-data.awk "${PEN_FILE}" 2>/dev/null)

PEN_WIDTH=$(awk -vFS='\t' '/Digitizer Pen\tDesktop X/ {print $12-$11; exit}' <<< "${PEN_DATA}")
PEN_HEIGHT=$(awk -vFS='\t' '/Digitizer Pen\tDesktop Y/ {print $12-$11; exit}' <<< "${PEN_DATA}")
PEN_X=$(awk -vFS='\t' '/Digitizer Pen\tDesktop X/ {print $6-$5; exit}' <<< "${PEN_DATA}")
PEN_Y=$(awk -vFS='\t' '/Digitizer Pen\tDesktop Y/ {print $6-$5; exit}' <<< "${PEN_DATA}")
PEN_RESX=$(awk -vFS='\t' '/Digitizer Pen\tDesktop X/ {printf("%.0f", ($6-$5) / ($12-$11)); exit}' <<< "${PEN_DATA}")
PEN_RESY=$(awk -vFS='\t' '/Digitizer Pen\tDesktop Y/ {printf("%.0f", ($6-$5) / ($12-$11)); exit}' <<< "${PEN_DATA}")
SENSORTYPE=$(grep "Digitizer Battery Strength" <<< "${PEN_DATA}" > /dev/null && echo "AES" || echo "EMR")
TILT_SUPPORT=$(grep "Digitizer X Tilt" <<< "${PEN_DATA}" > /dev/null && echo "Tilt" || true)
TOUCH_SUPPORT=$(test -n "${TOUCHSCREEN_FILE}" && echo "Touch" || true)
if [[ -n "${TOUCH_SUPPORT}" ]]; then
    TOUCH_SUPPORT="${TOUCH_SUPPORT} "$(test "${PEN_ID}" == "${TOUCHSCREEN_ID}" && echo "(Integrated)" || echo "(External)")
fi

FEATURES="${TOUCH_SUPPORT}#${TILT_SUPPORT}"
FEATURES=$(sed -E 's/#+/, /g; s/^, //; s/, $//' <<< ${FEATURES})

LIBWACOM_NOTE=$(cat <<-EOF
	# ${OEM} ${PRODUCT}
	# Sensor Type: ${SENSORTYPE}
	# Features: ${FEATURES}
	# HW Resolution: ${PEN_X} x ${PEN_Y} (${PEN_RESX} x ${PEN_RESY} lpi)
	#
	# Autogenerated from ${IDENT}
	# ${REF}
	EOF
)

LIBWACOM_NAME="ISDv4 ${PEN_PID}"
LIBWACOM_MATCH=${PEN_ID}
LIBWACOM_CLASS="ISDV4"
if [[ ${SENSORTYPE} == "AES" ]]; then
    LIBWACOM_STYLI="Styli=@isdv4-aes;"
elif [[ ${SENSORTYPE} == "EMR" ]]; then
    # No default stylus entry required
    true
fi
LIBWACOM_WIDTH=$(printf '%.0f\n' ${PEN_WIDTH})
LIBWACOM_HEIGHT=$(printf '%.0f\n' ${PEN_HEIGHT})
LIBACOM_INTEGRATION="Display;System"
if [[ -n "${TOUCH_SUPPORT}" ]]; then
    LIBWACOM_HASTOUCH="true"
    if [[ "${PEN_ID}" != "${TOUCHSCREEN_ID}" ]]; then
        LIBWACOM_MATCH="${LIBWACOM_MATCH}"$'\n'"PairedID=${TOUCHSCREEN_ID}"
    fi
else
    LIBWACOM_HASTOUCH="false"
fi


LIBWACOM_PREFIX="isdv4-"
if [[ ${PEN_VID} != "056a" ]]; then
    LIBWACOM_PREFIX="${LIBWACOM_PREFIX}${PEN_VID}-"
else
    LIBWACOM_PREFIX="wacom-${LIBWACOM_PREFIX}"
    LIBWACOM_NAME="Wacom ISDv4 ${PEN_PID}"
fi
LIBWACOM_FILE=$(tr A-Z a-z <<<"${LIBWACOM_PREFIX}${PEN_PID}.tablet")

####################
# Create tablet definition file
#
cat <<-EOF > "${LIBWACOM_FILE}"
	${LIBWACOM_NOTE}
	
	[Device]
	Name=${LIBWACOM_NAME}
	ModelName=${LIBWACOM_MODEL}
	DeviceMatch=${LIBWACOM_MATCH}
	Class=${LIBWACOM_CLASS}
	Width=${LIBWACOM_WIDTH}
	Height=${LIBWACOM_HEIGHT}
	IntegratedIn=${LIBACOM_INTEGRATION}
	${LIBWACOM_STYLI}

	[Features]
	Stylus=true
	Touch=${LIBWACOM_HASTOUCH}
	Buttons=0
	EOF

echo "Generated '${WORKDIR}/${LIBWACOM_FILE}'"
