#!/bin/sh

# Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
# All rights reserved.
# Confidential and Proprietary - Qualcomm Technologies, Inc.

# This script launches nativehaltest with automatic SoC detection
# Compatible with /bin/sh (POSIX)

# ============================================================================
# EXIT CODES
# ============================================================================
# 0  - Success (help displayed or test completed successfully)
# 1  - Cannot read SoC ID file (/sys/devices/soc0/soc_id)
# 2  - Unsupported SoC ID (not in the supported list)
# 3  - nativehaltest executable not found or not executable
# 4  - JSON test file not found
# 5  - Camera overlay driver not detected
# 64 - Too many arguments (expected 0 or 1 argument)
# N  - Passthrough exit code from nativehaltest (if test fails)
# ============================================================================

SOC_ID_FILE="/sys/devices/soc0/soc_id"

# Family defaults (can be tuned)
DEFAULT_COMMON_JSON="NHX.YUV_NV12_Prev_MaxRes"

# ============================================================================
# SoC FAMILY CONFIGURATION - SINGLE SOURCE OF TRUTH
# ============================================================================
# To add a new SoC family or ID, simply add/modify entries here.
# Format: "family_name | soc_ids | directory"
# - family_name: Display name for the SoC family
# - soc_ids: Comma-separated list of SoC IDs (no spaces)
# - directory: Subdirectory name appended to /usr/libexec/camx-
# ============================================================================
SOC_FAMILIES="
Kodiak  | 497,498,575      | kodiak
Lemans  | 534,667,676      | lemans
Monaco  | 606,674,675      | lemans
Talos   | 680              | talos
Hamoa   | 709,710          | hamoa
Purwa   | 711              | hamoa
Glymur  | 662,698,699,719  | glymur
Nord    | 648,690,691,692  | nord
Shikra  | 756,758,759      | shikra
"
#Kodiak, Lemans, Monaco, Talos, Hamoa, Purwa binaries are supported for Ubuntu distribution

# ============================================================================
# HELPER FUNCTIONS
# ============================================================================

# Get all supported SoC IDs as a comma-separated string
get_all_soc_ids() {
    echo "${SOC_FAMILIES}" | grep -v '^$' | while IFS='|' read -r name soc_ids dir; do
        soc_ids=$(echo "$soc_ids" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        [ -n "${soc_ids}" ] && echo "${soc_ids}"
    done | tr '\n' ',' | sed 's/,$//' | tr ',' ' '
}

# Look up SoC family configuration by SoC ID
# Returns: "family_name|soc_ids|directory" or empty if not found
lookup_soc_family() {
    target_id="$1"
    echo "${SOC_FAMILIES}" | grep -v '^$' | while IFS='|' read -r name soc_ids dir; do
        # Trim whitespace from each field
        name=$(echo "$name" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        soc_ids=$(echo "$soc_ids" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        dir=$(echo "$dir" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')

        # Check if target_id is in the comma-separated soc_ids list
        for id in $(echo "${soc_ids}" | tr ',' ' '); do
            if [ "${id}" = "${target_id}" ]; then
                echo "${name}|${soc_ids}|${dir}"
                return 0
            fi
        done
    done
}

# Generate usage text dynamically from SOC_FAMILIES
generate_usage_families() {
    echo "${SOC_FAMILIES}" | grep -v '^$' | while IFS='|' read -r name soc_ids dir; do
        # Trim whitespace
        name=$(echo "$name" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        soc_ids=$(echo "$soc_ids" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')

        [ -z "${soc_ids}" ] && continue
        # Format SoC IDs for display
        display_ids=$(echo "${soc_ids}" | tr ',' '/')
        printf "      * %-25s -> %s\n" "${name} (${display_ids})" "${DEFAULT_COMMON_JSON}"
    done
}

# Generate binary mapping text dynamically from SOC_FAMILIES
generate_usage_binaries() {
    echo "${SOC_FAMILIES}" | grep -v '^$' | while IFS='|' read -r name soc_ids dir; do
        # Trim whitespace
        soc_ids=$(echo "$soc_ids" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        dir=$(echo "$dir" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')

        [ -z "${soc_ids}" ] && continue
        # Format SoC IDs for display
        display_ids=$(echo "${soc_ids}" | tr ',' ', ')
        printf "  - %-30s -> /usr/libexec/camx-%s/nativehaltest\n" "${display_ids}" "${dir}"
    done
}

usage() {
    echo "nativehaltest launcher"
    echo "Usage: $0 [JSON_FILENAME]"
    echo ""
    echo "Arguments:"
    echo "  JSON_FILENAME    Optional. JSON test file to run."
    echo ""
    echo "Behavior:"
    echo "  - Without arguments, selects a SoC-specific default JSON:"
    generate_usage_families
    echo "  - With a single argument, uses that JSON name verbatim."
    echo ""
    echo "SoC ID is read from: ${SOC_ID_FILE}"
    echo "Binary mapping:"
    generate_usage_binaries
}

# ============================================================================
# MAIN SCRIPT
# ============================================================================

# Handle help flag
if [ $# -gt 0 ]; then
    case "$1" in
        -h|--help)
            usage
            exit 0
            ;;
    esac
fi

# Read SoC ID
if [ ! -r "$SOC_ID_FILE" ]; then
    echo "Error: Cannot read SoC ID file: ${SOC_ID_FILE}"
    exit 1
fi

SOC_ID="$(cat "${SOC_ID_FILE}" 2>/dev/null | tr -d '[:space:]')"

# Look up SoC family configuration
SOC_CONFIG="$(lookup_soc_family "${SOC_ID}")"

if [ -z "${SOC_CONFIG}" ]; then
    ALL_IDS="$(get_all_soc_ids)"
    if [ -z "${ALL_IDS}" ]; then
        echo "Error: No supported SoC IDs configured in SOC_FAMILIES"
        exit 2
    fi
    echo "Error: Unsupported SoC ID '${SOC_ID}'. Supported IDs: ${ALL_IDS}"
    exit 2
fi

# Parse configuration
SOC_NAME="$(echo "${SOC_CONFIG}" | cut -d'|' -f1)"
NHX_DIR="/usr/libexec/camx-$(echo "${SOC_CONFIG}" | cut -d'|' -f3)"

# Determine JSON file to use (argument overrides SoC default)
if [ $# -eq 0 ]; then
    JSON_FILE="${DEFAULT_COMMON_JSON}"
elif [ $# -eq 1 ]; then
    JSON_FILE="$1"
else
    echo "Error: Too many arguments. Expected 0 or 1 argument."
    echo "Tip: Run with -h or --help for usage information."
    exit 64
fi

EXEC="${NHX_DIR}/nativehaltest"

# Validate executable
if [ ! -x "${EXEC}" ]; then
    if [ -f "${EXEC}" ]; then
        echo "Error: '${EXEC}' exists but is not executable."
    else
        echo "Error: nativehaltest not found at: ${EXEC}"
    fi
    exit 3
fi

# Validate JSON existence
JSON_FULL_PATH="/etc/camera/test/NHX/${JSON_FILE}.json"
if [ ! -f "${JSON_FULL_PATH}" ]; then
    echo "Error: JSON file not found: ${JSON_FULL_PATH}"
    exit 4
fi

# Check for camera overlay driver presence
CAMERA_OVERLAY_FOUND=0
if [ -d "/sys/class/video4linux" ]; then
    for dev in /dev/video*; do
        [ -e "${dev}" ] || continue
        mod=$(readlink -f "/sys/class/video4linux/$(basename "${dev}")/device/driver/module" 2>/dev/null)
        case "${mod}" in
            *camera*)
                CAMERA_OVERLAY_FOUND=1
                break
                ;;
        esac
    done
fi

if [ "${CAMERA_OVERLAY_FOUND}" -eq 0 ]; then
    echo "Error: No camera overlay driver detected. Ensure the camera driver is loaded."
    exit 5
fi

echo "Detected SoC ID: ${SOC_ID} (${SOC_NAME})"
echo "Using test app: ${EXEC}"
echo "Selected JSON: ${JSON_FILE}"
echo "Running: ${EXEC} --test=${JSON_FILE}"

"${EXEC}" --test="${JSON_FILE}"
EXIT_CODE=$?

if [ ${EXIT_CODE} -ne 0 ] ; then
    echo "nativehaltest exited with code ${EXIT_CODE}"
fi

exit ${EXIT_CODE}
