#!/bin/sh
#
# Manages /dev/net/tun, /dev/shm and /dev/pts.
#

. /etc/features.conf

start() {
	echo -n "Starting devices: "

    # from buildroot's inittab
    [ -d /dev/pts ] || /bin/mkdir -p /dev/pts
    /bin/mount /dev/pts

    if [ "$MOUNT_DEV_SHM" == "1" ]; then
        [ -d /dev/shm ] || /bin/mkdir -p /dev/shm
        /bin/mount /dev/shm || /bin/mount -t tmpfs /dev/shm
    fi

    #On some systems we've seen that the tun driver node shows up in /dev/tun instead of /dev/net/tun
    #For those systems copy the tun driver node to /dev/net which is where we expect it to be
    if [ -c /dev/tun ]; then
        mkdir -p /dev/net
        cp -ap /dev/tun /dev/net/
    fi

    #If there is still no /dev/net/tun, create the device node.
    if [ ! -c /dev/net/tun ]; then
        mkdir -p /dev/net
        mknod /dev/net/tun c 10 200
        chmod 0666 /dev/net/tun
    fi

    #Load the tun.ko kernel module, if needed.
    if ! grep -q "^tun " /proc/modules; then
        if [ -f /usr/local/lib/tun.ko ]; then
            insmod /usr/local/lib/tun.ko
        fi
    fi

	echo "OK"
}

stop() {
	echo -n "Stopping devices: "

    #Unload the tun.ko kernel module, if needed.
    if grep -q "^tun " /proc/modules; then
        if [ -f /usr/local/lib/tun.ko ]; then
            rmmod tun
        fi
    fi

    if [ "$MOUNT_DEV_SHM" == "1" ]; then
	    /bin/umount /dev/shm
    fi

	/bin/umount /dev/pts

	echo "OK"
}

restart() {
	stop
	start
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  *)
	echo "Usage: $0 {start|stop}"
	exit 1
esac

exit $?

