#!/bin/bash

# Define the script name for help messages
SCRIPT_NAME=$(basename "$0")

# Determine the directory where this script resides
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")

# Function to display help information
show_help() {
    cat << EOF
Usage: $SCRIPT_NAME [option] [arguments...]

Invokes the appropriate architecture-specific decoder script.

Options:
  --aarch64           Use the aarch64 decoder
  --arm7hf            Use the arm7hf decoder
  --i686              Use the i686 decoder
  --x86_64, --x86-64  Use the x86_64 decoder
  -h, --help          Display this help message and exit

All other parameters are forwarded directly to the sub-script.
EOF
}

if [ "$1" == "" ] ; then
    show_help
    exit 1
fi

# Initialize variables
ARCH_TARGET=""
FORWARD_ARGS=()

# Parse command-line arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help)
            show_help
            exit 0
            ;;
        --aarch64)
            ARCH_TARGET="aarch64"
            shift
            ;;
        --arm7hf)
            ARCH_TARGET="arm7hf"
            shift
            ;;
        --i686)
            ARCH_TARGET="i686"
            shift
            ;;
        --x86_64|--x86-64)
            ARCH_TARGET="x86_64"
            shift
            ;;
        *)
            # Collect all other arguments to forward without vetting
            FORWARD_ARGS+=("$1")
            shift
            ;;
    esac
done

# If no architecture flag was passed, auto-detect using the 'arch' command
if [[ -z "$ARCH_TARGET" ]]; then
    HOST_ARCH=$(arch 2>/dev/null)
    
    case "$HOST_ARCH" in
        aarch64)
            ARCH_TARGET="aarch64"
            ;;
        arm7hf|armv7l)
            ARCH_TARGET="arm7hf"
            ;;
        i686|i386)
            ARCH_TARGET="i686"
            ;;
        x86_64|x86-64)
            ARCH_TARGET="x86_64"
            ;;
        *)
            echo "Error: Unsupported or unrecognized host architecture '$HOST_ARCH'." >&2
            echo "Please explicitly specify the target architecture using a flag." >&2
            exit 1
            ;;
    esac
fi

# Construct the full path to the specific script to invoke
DECODE_SCRIPT="${SCRIPT_DIR}/decode-${ARCH_TARGET}.sh"

# Verify that the target script exists and is executable
if [ ! -x "$DECODE_SCRIPT" ]; then
    echo "Error: Decoder script '$DECODE_SCRIPT' not found or is not executable." >&2
    exit 1
fi

# Invoke the target script, forwarding all collected arguments
exec "$DECODE_SCRIPT" "${FORWARD_ARGS[@]}"
