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

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
ROOT_DIR=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)
CONFIG_FILE=${1:-"$HOME/Saleculator.properties"}
STATUS=0

pass() {
  printf 'PASS: %s\n' "$1"
}

warn() {
  printf 'WARN: %s\n' "$1"
}

fail() {
  printf 'FAIL: %s\n' "$1"
  STATUS=1
}

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

check_command() {
  name=$1
  if command -v "$name" >/dev/null 2>&1; then
    pass "$name found: $(command -v "$name")"
  else
    fail "$name is not on PATH"
  fi
}

printf 'Saleculator preflight\n'
printf 'Root: %s\n' "$ROOT_DIR"
printf 'Config: %s\n\n' "$CONFIG_FILE"

check_command java
if command -v java >/dev/null 2>&1; then
  java -version 2>&1 | sed 's/^/INFO: /'
  java_major=$(java -version 2>&1 | sed -n '1s/.*version "\([^"]*\)".*/\1/p' | awk -F. '{ if ($1 == "1") print $2; else print $1 }')
  java_major=${java_major:-0}
  if [ "$java_major" -lt 8 ] 2>/dev/null; then
    fail "Java 8 or newer is required; detected major version $java_major"
  else
    pass "Java major version is $java_major"
  fi
fi

[ -f "$ROOT_DIR/dist/Saleculator.jar" ] && pass "application jar exists" || fail "missing dist/Saleculator.jar; runtime package is incomplete"
[ -d "$ROOT_DIR/lib" ] && pass "lib directory exists" || fail "missing lib directory"
[ -f "$ROOT_DIR/lib/mysql-connector-java-5.1.7-bin.jar" ] && pass "legacy MySQL driver exists" || warn "legacy MySQL driver is missing"
[ -f "$ROOT_DIR/lib/mysql-connector-j-8.4.0.jar" ] && pass "current MySQL driver exists" || warn "current MySQL driver is missing"
[ -f "$ROOT_DIR/lib/jSerialComm-2.7.0.jar" ] && pass "jSerialComm exists" || warn "jSerialComm is missing; serial printers/scales may fail"
[ -f "$ROOT_DIR/lib/pi4j-core.jar" ] && pass "Pi4J exists" || warn "Pi4J is missing; Raspberry Pi GPIO features may fail"

ARCH=$(uname -m 2>/dev/null || printf unknown)
OS=$(uname -s 2>/dev/null || printf unknown)
printf 'INFO: OS=%s ARCH=%s\n' "$OS" "$ARCH"

if [ "$OS" = "Linux" ]; then
  if [ -f "$ROOT_DIR/lib/Linux/libhidapi-jni.so" ]; then
    pass "Linux HID native library exists"
  else
    warn "Linux HID native library is missing"
  fi

  if printf '%s' "$ARCH" | grep -Eq 'arm|aarch64'; then
    warn "Raspberry/ARM detected; verify native HID/RXTX libraries match this CPU architecture"
  fi

  for group_name in dialout lp gpio; do
    if id -nG 2>/dev/null | tr ' ' '\n' | grep -qx "$group_name"; then
      pass "current user is in $group_name group"
    else
      warn "current user is not in $group_name group; some serial/printer/GPIO devices may need it"
    fi
  done

  for device_path in /dev/ttyUSB0 /dev/ttyACM0 /dev/usb/lp0; do
    if [ -e "$device_path" ]; then
      if [ -r "$device_path" ] && [ -w "$device_path" ]; then
        pass "$device_path is readable/writable"
      else
        warn "$device_path exists but is not readable/writable by current user"
      fi
    fi
  done

  if command -v startx >/dev/null 2>&1; then
    pass "startx exists for appliance/kiosk boot"
  else
    warn "startx not found; kiosk boot needs Xorg/xinit or an existing graphical login"
  fi
fi

if [ -f "$CONFIG_FILE" ]; then
  pass "config file exists"
  db_url=$(prop 'db.URL' "$CONFIG_FILE")
  db_driver=$(prop 'db.driver' "$CONFIG_FILE")
  db_driverlib=$(prop 'db.driverlib' "$CONFIG_FILE")
  printer=$(prop 'machine.printer' "$CONFIG_FILE")
  scale=$(prop 'machine.scale' "$CONFIG_FILE")
  scanner=$(prop 'machine.scanner' "$CONFIG_FILE")

  [ -n "$db_url" ] && printf 'INFO: db.URL=%s\n' "$db_url" || warn "db.URL is blank"
  [ -n "$db_driver" ] && printf 'INFO: db.driver=%s\n' "$db_driver" || warn "db.driver is blank"
  [ -n "$printer" ] && printf 'INFO: machine.printer=%s\n' "$printer" || warn "machine.printer is blank"
  [ -n "$scale" ] && printf 'INFO: machine.scale=%s\n' "$scale"
  [ -n "$scanner" ] && printf 'INFO: machine.scanner=%s\n' "$scanner"

  if [ -n "$db_driverlib" ]; then
    case "$db_driverlib" in
      ./*) driver_path="$ROOT_DIR/${db_driverlib#./}" ;;
      /*) driver_path="$db_driverlib" ;;
      *) driver_path="$ROOT_DIR/$db_driverlib" ;;
    esac
    [ -f "$driver_path" ] && pass "db.driverlib exists: $driver_path" || warn "db.driverlib does not exist: $driver_path"
  else
    warn "db.driverlib is blank"
  fi

  if printf '%s' "$db_url" | grep -q '^jdbc:mysql:'; then
    if command -v mysqladmin >/dev/null 2>&1; then
      if mysqladmin ping --silent >/dev/null 2>&1; then
        pass "MySQL server responds to mysqladmin ping"
      else
        warn "mysqladmin found, but server did not respond to ping"
      fi
    else
      warn "mysqladmin not found; database reachability was not checked"
    fi
  fi
else
  warn "config file not found; app will use built-in defaults on first run"
fi

printf '\n'
if [ "$STATUS" -eq 0 ]; then
  printf 'Preflight completed without hard failures.\n'
else
  printf 'Preflight found hard failures.\n'
fi
exit "$STATUS"
