#!/bin/bash

CURR_DIR=$PWD
BOGEN_DIR=/opt/bogen
INCOMING_DIR=$BOGEN_DIR/incoming

NQ_U_NAME="NyqUpdate"
NQ_U_FE="tar.gz"
U_FILE="$NQ_U_NAME*.$NQ_U_FE"
NQ_U_PATH="$INCOMING_DIR/$NQ_U_NAME"
cd $BOGEN_DIR

# Specify the directory to search
search_directory="/opt/bogen/incoming"

# Ensure the directory exists
if [ ! -d "$search_directory" ]; then
    echo "Directory $search_directory does not exist."
    exit 1
fi

# Search for files with the NyqUpdate pattern in the specified directory
files=("$search_directory"/NyqUpdate-*.tar.gz)

# Initialize variables to store the highest version
highest_major=0
highest_minor=0
highest_build=0
highest_version_file=""

# Loop through the files and extract version information
for file in "${files[@]}"; do
    if [[ $file =~ NyqUpdate-([0-9]+)\.([0-9]+)\.([0-9]+)\.tar\.gz ]]; then
        major="${BASH_REMATCH[1]}"
        minor="${BASH_REMATCH[2]}"
        build="${BASH_REMATCH[3]}"
        
        # Compare with the current highest version
        if ((major > highest_major)) || \
           ((major == highest_major && minor > highest_minor)) || \
           ((major == highest_major && minor == highest_minor && build > highest_build)); then
            highest_major="$major"
            highest_minor="$minor"
            highest_build="$build"
            highest_version_file="$file"
        fi
    fi
done

# Display the highest version file and version number
if [ -n "$highest_version_file" ]; then
    echo "Highest version file: $highest_version_file"
    echo "Highest version: $highest_major.$highest_minor.$highest_build"
    
    # Remove all other NyqUpdate files
    for file in "${files[@]}"; do
        if [ "$file" != "$highest_version_file" ]; then
            echo "Removing $file"
            rm "$file"
        fi
    done

	tar -xzf $highest_version_file
else
    echo "No files matching the NyqUpdate pattern found in $search_directory."
fi


sudo chmod 755 update_firmware
sudo ./update_firmware

cd $CURR_DIR
