#!/bin/sh

CONFIG="/tmp/fw_env.config"
LOCK="/tmp/"

ln -s /tmp/fw_printenv /tmp/fw_setenv

# Create config file (if not exists)
echo "/dev/mtd0 0xc0000 0x40000 0x20000" > $CONFIG

# Get current bootargs
CURRENT_BOOTARGS=$(./fw_printenv -c $CONFIG -l $LOCK -n bootargs)

echo "Current bootargs: $CURRENT_BOOTARGS"

# Check if contains mem=1024M
if echo "$CURRENT_BOOTARGS" | grep -q "mem=1024M"; then
    echo "Detected mem=1024M, changing to mem=512M..."
    
    # Replace mem=1024M with mem=512M
    NEW_BOOTARGS=$(echo "$CURRENT_BOOTARGS" | sed 's/mem=1024M/mem=512M/g')
    
    echo "New bootargs: $NEW_BOOTARGS"
    
    # Set new bootargs
    ./fw_setenv -c $CONFIG -l $LOCK bootargs "$NEW_BOOTARGS"
    
    # Verify modification
    VERIFY_BOOTARGS=$(./fw_printenv -c $CONFIG -l $LOCK -n bootargs)
    if echo "$VERIFY_BOOTARGS" | grep -q "mem=512M"; then
        echo "Modification successful! System will reboot in 1 seconds..."
        sync
	sleep 1
        reboot -f
    else
        echo "Modification failed!"
        exit 1
    fi
else
    echo "bootargs already contains mem=512M or doesn't contain mem=1024M, no modification needed."
fi
