#!/bin/bash

# Define the file paths to check
CONF_FILE="/etc/mft/mft.conf"
JSON_FILES="/usr/share/mft/device_info/json/*.json"

# Get the absolute path of the script's directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Define the setup command path
SETUP_CMD="$SCRIPT_DIR/acpqsetup"
MFTTOOL_CMD="$SCRIPT_DIR/mlxfwmanager"

# Check if all files exist
if [[ -f "$CONF_FILE" && -n "$(ls $JSON_FILES 2>/dev/null)" ]]; then
    # If all files exist, run the setup command with any provided arguments
    chmod 755 "$SETUP_CMD"
    chmod 755 "$MFTTOOL_CMD"
    cd "$SCRIPT_DIR"
    "$SETUP_CMD" "$@"
else
    # If any file is missing, find and extract the mft-*.tgz file, then run the setup command
    TAR_FILE=$(find "$SCRIPT_DIR" -maxdepth 1 -name "mft-*.tgz" | head -n 1)
    TAR2_FILE=$(find "$SCRIPT_DIR" -maxdepth 1 -name "binx*.tgz" | head -n 1)
    
    if [[ -n "$TAR_FILE" ]]; then
        tar -xzvmf "$TAR_FILE" -C / >/dev/null 2>&1
        chmod 755 "$SETUP_CMD"
        chmod 755 "$MFTTOOL_CMD"
    	if [[ -x "$MFTTOOL_CMD" ]]; then
		 echo "mft tools permissions is excutable"
    	else
    		if [[ -n "$TAR2_FILE" ]]; then
    			cd "$SCRIPT_DIR"
        		tar -xzvmf "$TAR2_FILE" >/dev/null 2>&1
		fi
    	fi
	cd "$SCRIPT_DIR"
        "$SETUP_CMD" "$@"
    else
        echo "Error: mft-*.tgz not found in $SCRIPT_DIR"
        exit 1
    fi
    
fi
