#!/bin/sh
#
# /etc/init.d/rcS
#

mount -t proc none /proc

mount -t sysfs none /sys

if grep -q "quietinit" /proc/cmdline; then
	exec 1>/dev/null
fi

echo -n "attaching ubi"
# attach UBI partition
/usr/sbin/ubiattach /dev/ubi_ctrl -m 6 > /dev/null
retval=$?
if [ "$retval" -eq "0" ] ; then
mount /home/ > /dev/null
retval=$?
if [ "$retval" -ne "0" ] ; then
/usr/bin/recoverubifs.sh
fi
else
/usr/bin/recoverubifs.sh
fi
echo "done."

#setup writable file in /etc directory
mkdir -p /home/etc/ssh
mkdir -p /home/etc/rc.once.d/.done
mkdir -p /home/var_log

if [ ! -e /home/etc/localtime ]; then
    ln -s ../../usr/share/zoneinfo/Europe/Berlin /home/etc/localtime
fi

# check for if-up scripts before copying /etc/network/* as that would always create /home/etc/network/if-up.d/
if [ ! -e /home/etc/network/if-up.d -a ! -e /home/etc/network/if-up.d/dhcpserver ]; then
    mkdir -p /home/etc/network/if-up.d
    cp -af /etc/network/if-up.d/dhcpserver /home/etc/network/if-up.d/dhcpserver
fi
if [ ! -e /home/etc/network/if-down.d -a ! -e /home/etc/network/if-down.d/dhcpserver ]; then
    mkdir -p /home/etc/network/if-down.d
    cp -af /etc/network/if-down.d/dhcpserver /home/etc/network/if-down.d/dhcpserver
fi

if [ ! -e /home/etc/network/interfaces ]; then
    mkdir -p /home/etc/network
    cp -af /etc/network/* /home/etc/network/
fi
#if [ ! -e /home/etc/passwd ]; then
#    echo -n "Creating passwd and friends in /home/etc/..."
#    mkdir -p /home/etc/
#    cp -p /etc/passwd_default /home/etc/passwd
#    cp -p /etc/shadow_default /home/etc/shadow
#    cp -p /etc/group_default /home/etc/group
#    cp -p /etc/gshadow_default /home/etc/gshadow
#    sync
#    echo "done."
#fi

echo -n "mounting filesystems..."
mount -a 2>/dev/null
echo "done"

#enable alignment trap fixes
echo "2" > /proc/cpu/alignment

# set hostname
test -e /etc/hostname && hostname -F /etc/hostname

export OPENSSH_RSAKEY="/home/etc/ssh/ssh_host_rsa_key"
export OPENSSH_DSAKEY="/home/etc/ssh/ssh_host_dsa_key"

# set MAC address of eth0, which is stored in EEPROM
EEPROM="/sys/class/spi_master/spi1/spi1.0"
export EEPROM_DATA="${EEPROM}/eeprom"
eval $(cat ${EEPROM_DATA} | grep -m 1 -o -E 'MAC_ADDRESS=[0-9a-fA-F:]+')
[ -n "${MAC_ADDRESS}" ] && /sbin/ifconfig eth0 hw ether ${MAC_ADDRESS}

echo "running rc.d services..."
run-parts -a start /etc/rc.d

