#!/bin/bash

set -e

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

usage() {
    cat <<EOF
 Extract a sysinfo archive into a directory suitable for commit and
 auto-generate a tablet definition file.

 Usage: 
     git-update.sh <archive> <--url=<post> | --nourl> [--username=<name>] [--oem=<name>] [--product=<name>]

 archive           Path to the sysinfo archive to be processed
 --url=<post>      Link to the post which produced this archive
 --nourl           Explicitly do not reference a public sysinfo posting
 --username=<name> Set the Github username of the source
 --oem=<name>      Override the OEM name contained in machine.txt
 --product=<name>  Override the product name contained in machine.txt
EOF
}

####################
# Dependency check
#
if ! command -v hidrd-convert 2>&1 > /dev/null; then
  echo "ERROR: Could not find required 'hidrd-convert' tool. Check your distro packages or"
  echo "install from source: https://github.com/DIGImend/hidrd"
  exit 1
fi

####################
# Argument parsing
#
if [[ $# -lt 2 ]]; then
  echo "ERROR: Required arguments missing."
  echo
  usage
  exit 1
fi

for arg in "${@}"; do
  case $arg in
    --url=*) ISSUE_URL="${arg#*=}"; shift;;
    --nourl) NOURL=1; shift;;
    --username=*) SOURCE_USERNAME="${arg#*=}"; shift;;
    --oem=*) OEM="${arg#*=}"; shift;;
    --product=*) PRODUCT="${arg#*=}"; shift;;
    *) ARCHIVE=$(readlink -f "${arg}"); shift;;
  esac
done

IDENT=$(tar --list -f "${ARCHIVE}" | head -n1)
IDENT=${IDENT%/}
MACHINE=$(tar xf "${ARCHIVE}" -O ${IDENT}/machine.txt)

if [[ -n "${NOURL}" ]]; then
  echo "NOTE: Treating as a private bug..."
  ISSUE_URL="From private bug report"
elif [[ -z "${ISSUE_URL}" ]]; then
  echo "ERROR: The --url=<issue> parameter is required."
  echo
  usage
  exit 1
elif [[ "${ISSUE_URL}" != *"github"* ]]; then
  echo "ERROR: This script can only handle Github issues."
  exit 1
fi

if [[ -z "${OEM}" ]]; then
  OEM=$(awk -F: '/\/chassis_vendor/ {print $2}' <<< "${MACHINE}")
  case "${OEM}" in
    "Acer")                  OEM="Acer";;
    "Dell Inc.")             OEM="Dell";;
    "FUJITSU")               OEM="Fujitsu";;
    "Google")                OEM="Google";;
    "Hewlett-Packard")       OEM="HP";;
    "HP")                    OEM="HP";;
    "LENOVO")                OEM="Lenovo";;
    "Microsoft Corporation") OEM="Microsoft";;
    "SAMSUNG ELECTRONICS CO., LTD.") OEM="Samsung";;
    "Motion Computing")      OEM="Motion Computing";;
    "MOTION")                OEM="Motion Computing";;
    "ASUSTeK COMPUTER INC.") OEM="ASUS";;
    "HUAWEI")                OEM="Huawei";;
    "Panasonic Corporation") OEM="Panasonic";;
    "TOSHIBA")               OEM="Toshiba";;
    *)                       echo "ERROR: Unknown OEM '${OEM}'. Please specify one with the --oem=<name> argument."; exit 1;;
  esac
fi

if [[ -z "${PRODUCT}" ]]; then
  if [[ "${OEM}" = "Lenovo" ]]; then
    PRODUCT=$(awk -F: '/\/product_family/ {print $2}' <<< "${MACHINE}")
  else
    PRODUCT=$(awk -F: '/\/product_name/ {print $2}' <<< "${MACHINE}")
  fi

  if [[ -z "${PRODUCT}" ]]; then
    echo "ERROR: Unable to determine product name. Please specify one with the --product=<name> argument."
    exit 1
  fi
fi

if [[ "${PRODUCT}" =~ "${OEM} "* ]]; then
    echo "NOTE: Removing manufacturer from product name..."
    PRODUCT=${PRODUCT#"${OEM} "}
fi

echo "Manufacturer: \"${OEM}\""
echo "Product: \"${PRODUCT}\""
while true; do
  read -p "Is this correct? (Y/N) " yn
  case $yn in
    [Yy]*) break;;
    [Nn]*)
      echo "ERROR: Please specify OEM and/or product with the --oem=<name> and --product=<name> arguments."
      exit 1;;
    *);;
  esac
done



####################
# Extract archive into proper directory
#
if [[ ! -d "${OEM} ${PRODUCT}" ]]; then
  mkdir "${OEM} ${PRODUCT}"
fi
cd "${OEM} ${PRODUCT}"
tar xf "${ARCHIVE}"



####################
# Process archive: extract and convert data
#
ARCHIVE_DATE=$(date -r "${IDENT}" +%Y-%m-%d)

if test $(ls "${IDENT}/"*.hid.bin 2>/dev/null | wc -l) -gt 0; then
  for F in "${IDENT}/"*.hid.bin; do
    hidrd-convert -i natv -o spec "${F}" > "${F%bin}txt"
    hidrd-convert -i natv -o xml "${F}" > "${F%bin}xml"
  done
fi

# Find the Wacom pen sensor
# Create a device ID (e.g. "i2c:056a:1234")
# Determine width and height in inches
# Create tablet definition



####################
# Create/update README file
#
if [[ ! -f "README" ]]; then
  NOTES=""

  cat <<-EOF > README
	Manufacturer: ${OEM}
	Model Name: ${PRODUCT}
	Model Number:
	
	Notes: ${NOTES}
	
	Source(s):
	EOF
fi

if [[ -z "${NOURL}" ]]; then
  if [[ -z "${SOURCE_USERNAME}" ]]; then
    ANCHOR="#${ISSUE_URL#*#}"
    if [[ "$ANCHOR" = "#${ISSUE_URL}" ]]; then
      SOURCE_USERNAME=$(curl "${ISSUE_URL}" | sed -En 's!^.+"issue-body-header-author">([^<]+).+$!\1!p' | head -n1)
    else
      echo "Error: Unable to find username in source URL. Please provide --username argument."
      exit 1
    fi
  fi
  USER_URL="https://github.com/${SOURCE_USERNAME}"
  SOURCE_INFO=$(cat <<-EOF
	* ${IDENT}
	  ${SOURCE_USERNAME} [${USER_URL}]
	  ${ISSUE_URL}
	  ${ARCHIVE_DATE}
	
	EOF
    )
else
  SOURCE_INFO=$(cat <<-EOF
	* ${IDENT}
	  ${ISSUE_URL}
	  ${ARCHIVE_DATE}
	
	EOF
    )
fi
echo "Attributing data as:"
echo "$SOURCE_INFO"
echo "$SOURCE_INFO" >> README

echo "Generated '$(pwd)/README'"

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

${SCRIPTDIR}/gen-libwacom.sh --ref="${ISSUE_URL}" --oem="${OEM}" --product="${PRODUCT}" "${IDENT}"
