#!/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
# Default JSON: NHX.YUV_NV12_Prev_MaxRes
# Compatible with /bin/sh (POSIX)

SOC_ID_FILE="/sys/devices/soc0/soc_id"
DEFAULT_JSON="NHX.YUV_NV12_Prev_MaxRes"

usage() {
    echo "nativehaltest launcher"
    echo "Usage: $0 [JSON_FILENAME]"
    echo ""
    echo "Arguments:"
    echo "  JSON_FILENAME    Optional. JSON test file to run (default: $DEFAULT_JSON)"
    echo ""
    echo "SoC ID is read from: $SOC_ID_FILE"
    echo "Mapping:"
    echo "  - 497, 498, 575 -> /usr/bin/camx/kodiak/nativehaltest"
    echo "  - 534, 667, 676, 606, 675, 674 -> /usr/bin/camx/lemans/nativehaltest"
}

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

# Determine JSON file to use
if [ $# -eq 0 ]; then
    JSON_FILE="$DEFAULT_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

# 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:]')"

# Map SoC ID to executable directory
case "$SOC_ID" in
    497|498|575)
        NHX_DIR="/usr/bin/camx/kodiak"
        ;;
    534|667|676|606|675|674)
        NHX_DIR="/usr/bin/camx/lemans"
        ;;
    *)
        echo "Error: Unsupported SoC ID '$SOC_ID'. Supported IDs: 497, 498, 575, 534, 667, 676, 606, 675, 674"
        exit 2
        ;;
esac

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

# Optional: Warn if JSON file isn't present locally
JSON_FULL_PATH="/etc/camera/test/NHX/$JSON_FILE.json"
if [ ! -f "$JSON_FULL_PATH" ]; then
    echo "Warning: JSON file not found: $JSON_FULL_PATH"
    exit 4
fi

echo "Detected SoC ID: $SOC_ID"
echo "Using test app: $EXEC"
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