#!/bin/sh

# If there is no hwinfo, we should create it, using the default
# file and the currently-active mac addresses. This is a hack to help
# people upgrading from older wr-switch-sw releases.
#
# This script is run late, because it will have effect at next boot only.
# If we run it too early, we can't get the mac address from wr0 which does
# not exist yet.

# This allows me to pass WRS_VERBOSE=y on the command line...
if [ -n "$WRS_VERBOSE" ]; then
    set -x
fi

# will be changed later if successful
echo "hwinfo_error" > /tmp/hwinfo_read_status

# This kernel has no hwinfo partition (strange...)
if ! grep -q hwinfo /proc/mtd; then
    # probably not an error, save script result for snmp
    echo "hwinfo_warning" > /tmp/hwinfo_read_status
    exit 0;
fi

# Is there sdb in there? If so, nothing to do.
if /wr/bin/sdb-read /dev/mtd5ro > /dev/null; then
    # save script result for snmp
    echo "hwinfo_ok" > /tmp/hwinfo_read_status
    exit 0;
fi

echo "Creating SDB filesystem in /dev/mtd5"

# So, we must create an sdb file, we need the template
cp /wr/etc/sdb-for-dataflash /tmp || exit 1

# we need the eth addresses
ethaddr=$(ifconfig eth0 | grep HWaddr | awk '{print $5}')
wraddr=$(ifconfig wr0 | grep HWaddr | awk '{print $5}')

# if we run this early (upgrade mess from v4.0) there is no wr0,
# so pick if from the command line:
if [ "x$wraddr" = "x" ]; then
    wraddr=$(awk 'BEGIN {FS="="; RS=" "} /wr_nic.macaddr/ {print $2}' \
	/proc/cmdline)
fi
# and, to be super-pedantic, if empty use default and don't corrupt hwinfo
if [ "x$ethaddr" = "x" ]; then ethaddr="02:34:56:78:9A:BC"; fi
if [ "x$wraddr"  = "x" ]; then  wraddr="02:34:56:78:9A:00"; fi

# we lack sdb-write...
sed -i s,02:34:56:78:9A:BC,$ethaddr, /tmp/sdb-for-dataflash
sed -i s,02:34:56:78:9A:00,$wraddr,  /tmp/sdb-for-dataflash

# Create the writable device file and write in there, then remove it
test -c /dev/mtd5 || mknod /dev/mtd5 c 90 10
flash_erase /dev/mtd5 0 0
cat /tmp/sdb-for-dataflash > /dev/mtd5
rm /dev/mtd5

# save script result for snmp
echo "hwinfo_ok" > /tmp/hwinfo_read_status
