#!/bin/sh

mkdir -p /dev/

if ! test -c /dev/null ; then
    mknod /dev/null c 1 3
    chmod 666 /dev/null
fi

if ! test -c /dev/zero ; then
    mknod /dev/zero c 1 5
    chmod 666 /dev/zero
fi

if ! test -c /dev/random ; then
    mknod /dev/random c 1 8
    chmod 666 /dev/random
fi

if ! test -c /dev/urandom ; then
    mknod /dev/urandom c 1 9
    chmod 666 /dev/urandom
fi

if ! test -c /dev/tty ; then
    mknod /dev/tty c 5 0
    chmod 666 /dev/tty
fi

if ! test -c /dev/console ; then
    mknod /dev/console c 5 1
    chmod 600 /dev/console
fi

if ! test -c /dev/ptmx ; then
    mknod /dev/ptmx c 5 2
    chmod 666 /dev/ptmx
fi

if test "$(uname -s)" = 'Linux' ; then

    mounts="$(mount)"

    check_correct_proc="$(printf "%s" "${mounts}" | grep -e '/proc' )"
    if test -n "${check_correct_proc}" -a ! -h /proc/self ; then
        # mount reports /proc existing, but it does not.
        # that means broken local mtab
        if test ! -h /etc/mtab ; then
            rm /etc/mtab
        fi
        mounts=
    fi

    if test -z "$(printf "%s" "${mounts}" | grep -e '/dev/shm' )" ; then
        mkdir -p /dev/shm
        chmod 1777 /dev/shm
        mount -o rw,noexec,nodev,nosuid -t tmpfs tmpfs /dev/shm
    fi

    if test -z "$(printf "%s" "${mounts}" | grep -e '/dev/pts' )" ; then
        mkdir -p /dev/pts
        mount -o rw,noexec,nosuid,gid=5,mode=620 -t devpts devpts /dev/pts
    fi

    if test -z "$(printf "%s" "${mounts}" | grep -e '/proc' )" ; then
        mkdir -p /proc
        mount -o ro,noexec,nodev,nosuid -t proc proc /proc
    fi
    if test ! -h /etc/mtab -a ! -f /etc/mtab ; then
        ln -s ../proc/self/mounts /etc/mtab
    fi
    if test ! -h /dev/fd ; then
        ln -s ../proc/self/fd /dev/fd
    fi

fi
