#!/usr/bin/env sh
set -u

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
ROOT_DIR=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)
CONFIG_FILE=${1:-"${SALECULATOR_CONFIG:-$HOME/Saleculator.properties}"}
OUT_FILE="$ROOT_DIR/support-info-$(date +%Y%m%d-%H%M%S).txt"

prop() {
  key=$1
  file=$2
  [ -f "$file" ] || return 0
  sed -n "s/^[[:space:]]*$key[[:space:]]*=[[:space:]]*//p" "$file" | tail -n 1
}

mask_value() {
  key=$1
  value=$2
  case "$key" in
    *password*|*PASSWORD*|*token*|*TOKEN*|*key*|*KEY*|*secret*|*SECRET*)
      [ -n "$value" ] && printf '<configured>' || printf ''
      ;;
    *)
      printf '%s' "$value"
      ;;
  esac
}

{
  echo "Saleculator Support Info"
  echo "Generated: $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
  echo "Root: $ROOT_DIR"
  echo "Config: $CONFIG_FILE"
  echo

  echo "[release]"
  if [ -f "$ROOT_DIR/release-info.properties" ]; then
    cat "$ROOT_DIR/release-info.properties"
  else
    echo "release-info.properties=missing"
  fi
  echo

  echo "[os]"
  uname -a 2>/dev/null || true
  [ -f /etc/os-release ] && cat /etc/os-release
  echo "user=$(id 2>/dev/null || true)"
  echo "groups=$(id -nG 2>/dev/null || true)"
  echo

  echo "[java]"
  if command -v java >/dev/null 2>&1; then
    command -v java
    java -version 2>&1
  else
    echo "java=missing"
  fi
  echo

  echo "[package]"
  [ -f "$ROOT_DIR/dist/Saleculator.jar" ] && ls -l "$ROOT_DIR/dist/Saleculator.jar" || echo "jar=missing"
  [ -d "$ROOT_DIR/lib" ] && echo "lib.count=$(find "$ROOT_DIR/lib" -type f | wc -l)" || echo "lib=missing"
  [ -f "$ROOT_DIR/lib/mysql-connector-java-5.1.7-bin.jar" ] && echo "mysql.legacy=present" || echo "mysql.legacy=missing"
  [ -f "$ROOT_DIR/lib/mysql-connector-j-8.4.0.jar" ] && echo "mysql.current=present" || echo "mysql.current=missing"
  [ -f "$ROOT_DIR/lib/jSerialComm-2.7.0.jar" ] && echo "jSerialComm=present" || echo "jSerialComm=missing"
  [ -f "$ROOT_DIR/lib/pi4j-core.jar" ] && echo "pi4j=present" || echo "pi4j=missing"
  echo

  echo "[config]"
  if [ -f "$CONFIG_FILE" ]; then
    echo "config.exists=true"
    for key in db.URL db.driver db.driverlib db.user db.password machine.printer machine.scale machine.scanner machine.screenmode remoteaccess.webin.enabled remoteaccess.webin.remotehost; do
      value=$(prop "$key" "$CONFIG_FILE")
      echo "$key=$(mask_value "$key" "$value")"
    done
  else
    echo "config.exists=false"
  fi
  echo

  echo "[devices]"
  for path in /dev/ttyUSB* /dev/ttyACM* /dev/usb/lp* /dev/hidraw*; do
    [ -e "$path" ] && ls -l "$path"
  done
  command -v lsusb >/dev/null 2>&1 && lsusb || echo "lsusb=unavailable"
  echo

  echo "[kiosk]"
  if command -v systemctl >/dev/null 2>&1; then
    systemctl status saleculator-kiosk.service --no-pager 2>&1 || true
    journalctl -u saleculator-kiosk.service -n 80 --no-pager 2>&1 || true
  else
    echo "systemctl=unavailable"
  fi
} > "$OUT_FILE"

echo "$OUT_FILE"
