#!/bin/bash

# Check if the user provided the correct number of command line arguments
if [ "$#" -lt 3 ]; then
    echo "Usage: $0 <operation> <address> <length/data> [string flag]"
    echo ""
    echo "operation: Specifies the type of operation."
    echo "  -r: Read data from the EEPROM."
    echo "  -w: Write data to the EEPROM."
    echo ""
    echo "address: The starting address of the EEPROM."
    echo ""
    echo "length/data: Depending on the type of operation, this parameter has two uses:"
    echo "  If the operation is -r, this parameter represents the length of the data to read."
    echo "  If the operation is -w, this parameter represents the data to write to the EEPROM."
    echo ""
    echo "string flag: An optional parameter that indicates whether the data is a string."
    echo "  -s: If this parameter is present, it indicates that the data is a string. In the write operation, a null character will be added at the end of the data. In the read operation, reading will stop when a null character is encountered."
    exit 1
fi

# Parse the command line arguments
op=$1
addr=$2
data_or_len=$3
is_string=$4

# Determine the operation
if [ "$op" = "-w" ]; then
    # Write the data to the EEPROM
    if [ "$is_string" = "-s" ]; then
        # If the data is a string, add a null character at the end
        printf "%s\0" "$data_or_len" | eeprog -f -16 -w $addr -t 5 /dev/i2c-2 0x50 > /dev/null 2>&1 || { echo "Failed to write to EEPROM"; exit 1; }
    else
        echo -n "$data_or_len" | eeprog -f -16 -w $addr  -t 5 /dev/i2c-2 0x50 > /dev/null 2>&1 || { echo "Failed to write to EEPROM"; exit 1; }
    fi

elif [ "$op" = "-r" ]; then
    # Read the data from the EEPROM
    len=$data_or_len

    # Read the data from the EEPROM and print it
    if [ "$is_string" = "-s" ]; then
        # If the data is a string, print until the null character
        eeprog -f -16 -r $addr:$len /dev/i2c-2 0x50 2>/dev/null | awk -v RS='\0' 'NR==1{print}' || { echo "Failed to read from EEPROM"; exit 1; }
    else
        eeprog -f -16 -r $addr:$len /dev/i2c-2 0x50 2>/dev/null || { echo "Failed to read from EEPROM"; exit 1; }
    fi
else
    echo "Invalid operation. Use -r for read and -w for write."
    exit 1
fi
