#!/usr/bin/env bash

MODULE_HARDWARE_DETECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULE_HARDWARE_DETECT_PROJECT_ROOT="$(cd "$MODULE_HARDWARE_DETECT_DIR/../../.." && pwd)"

# shellcheck source=lib/package.sh
source "$MODULE_HARDWARE_DETECT_PROJECT_ROOT/lib/package.sh"
# shellcheck source=modules/hardware/detect/config.sh
source "$MODULE_HARDWARE_DETECT_DIR/config.sh"
# shellcheck source=modules/hardware/detect/metadata.conf
source "$MODULE_HARDWARE_DETECT_DIR/metadata.conf"

module_detect_metadata() {
  printf '%s|%s|%s\n' "$MODULE_ID" "$MODULE_NAME" "$MODULE_DESCRIPTION"
}

module_detect_install() {
  package_refresh_indexes
  package_install lshw pciutils usbutils dmidecode

  mkdir -p "$(dirname "$POSTINSTALL_HARDWARE_DETECT_REPORT_FILE")"
  {
    printf '== lshw -short ==\n'
    lshw -short 2>/dev/null || true
    printf '\n== lspci ==\n'
    lspci 2>/dev/null || true
    printf '\n== lsusb ==\n'
    lsusb 2>/dev/null || true
    printf '\n== dmidecode -t system ==\n'
    dmidecode -t system 2>/dev/null || true
  } > "$POSTINSTALL_HARDWARE_DETECT_REPORT_FILE"

  log_info "Rapport hardware genere : $POSTINSTALL_HARDWARE_DETECT_REPORT_FILE"
  ui_success "Rapport hardware genere"
}

module_detect_test() {
  package_is_installed lshw || return 1
  package_is_installed pciutils || return 1
  package_is_installed usbutils || return 1
  package_is_installed dmidecode || return 1
  test -s "$POSTINSTALL_HARDWARE_DETECT_REPORT_FILE"
}
