#!/bin/sh

if [ "$1" = "stop" ]
then
    echo Unmounting filesystems
    umount -a -r
    /usr/bin/ubidetach -p /dev/mtd5
    mount -o remount -r %root% /
    [ -x /sbin/swapoff ] && swapoff -a
fi

if [ "$1" = "start" ]
then
    echo Mounting filesystems
    if [ "$TMPFS" = "tmpfs" ]
    then
        mount -n -t $TMPFS shm /dev/shm
    fi
    if [ -n "$TMPFS" ]
    then
        mount -n -t $TMPFS rwfs /mnt/rwfs -o size=$TMPFS_SIZE
    fi
    
    # +TPE+ start: always mount NFS rw
    NFSBOOT="`cat /proc/cmdline | grep -q /dev/nfs ; echo $?`"
    if [ "$NFSBOOT" == "0" ]
    then
        echo Booted NFS, mounting rootfs rw
        mount -n -o remount -w %root% /
        RAMDIRS=""
    elif [ "$READONLY_FS" != "y" ]
    then
        mount -n -o remount -w %root% /
    else
        # initramfs, ramdisks, others? come up read/write by default
        mount -n -o remount -r %root% /
        RAMDIRS="$RAMDIRS /tmp /etc /var /disk"
    fi
    # +TPE+ end: always mount NFS rw
    
    if [ -n "$RAMDIRS" ]
    then
        for i in $RAMDIRS
        do
            if [ ! -e /mnt/rwfs/$i ]
            then
                cp -a $i /mnt/rwfs/
                mount -n -o bind /mnt/rwfs/$i $i
            fi
        done
    fi
    if [ -e /etc/mtab ]
    then
        rm -f /etc/mtab
    fi
    ln -s /proc/mounts /etc/mtab
    if [ ! -d /dev/pts ]
    then
        mkdir /dev/pts
    fi
    
    # attach UBI devices
    echo "Attaching UBI devices"
    /usr/bin/ubiattach -d 1 -p /dev/mtd5
    usleep 10000
    
    # format UBI device on first start
    if [ ! -e /dev/ubi1_0 -a ! -e /dev/ubi1_1 ]
    then
        echo "Formatting UBI device, this is only done once ..."
        /usr/bin/ubidetach -p /dev/mtd5
        /usr/bin/ubiformat /dev/mtd5 -y
        /usr/bin/ubiattach -d 1 -p /dev/mtd5
        usleep 10000
    fi
    
    # create UBI volume 0 (diagnostic)
    if [ ! -e /dev/ubi1_0 ]
    then
        echo "Creating diagnostic UBI volume"
        /usr/bin/ubimkvol /dev/ubi1 -s 12MiB -N diagnostic
    fi
    
    # create UBI volume 1 (user)
    if [ ! -e /dev/ubi1_1 ]
    then
        echo "Creating user UBI volume"
        /usr/bin/ubimkvol /dev/ubi1 -m -N user
    fi
    
    mount -a
    
    # Retrigger block devices, required to auto mount USB Flash
    # drives already connected during boot, because /disk was
    # not writeable before execution of this script.
    udevtrigger --subsystem-match=block
fi
