#! /bin/sh

export PATH=/bin:/sbin:/usr/bin:/usr/sbin

. /etc/config

if [ -z "$cfg_tmpfs_size" ]; then
    cfg_tmpfs_size='2097152'
fi

if [ -z "$cfg_min_free_kbytes" ]; then
    cfg_min_free_kbytes='8192'
fi

sysinit()
{
    if [ -f /.reboot ]; then
        mount -t proc proc /proc
        mount -o remount,rw /
        rm /.reboot
        mount -o remount,ro /
        reboot
        return 0
    fi

# Mount pseudo-filesystems.
    mount -t sysfs sysfs /sys &&
    mount -t proc proc /proc &&
    mkdir /dev/shm /dev/pts &&
    mount -t tmpfs -o size="$cfg_tmpfs_size" tmpfs /dev/shm &&
    mount -t devpts devpts /dev/pts &&

# Register mdev as hotplug event handler.
    echo >/dev/mdev.seq &&
    echo /sbin/mdev > /proc/sys/kernel/hotplug &&

# Update ld cache, populate /dev.
#    mount -o remount,rw / &&
    /sbin/mdev -s &&
#    /sbin/ldconfig &&
#    mount -o remount,ro / &&

# Set minimum free kbytes.
    echo "$cfg_min_free_kbytes" > /proc/sys/vm/min_free_kbytes &&

# Set hostname.
    hostname "$cfg_hostname" &&

# Loopback device.
    ifconfig lo 127.0.0.1 netmask 255.0.0.0 up &&

# Load modules.
    modprobe -a $cfg_modules $cfg_modules1

# Start services.
    for service in $cfg_services0 $cfg_services1 $cfg_services2; do
        . /etc/rc.d/$service
        start
    done
}

syshalt()
{
    if [ -f /.reboot ]; then
        return 0
    fi

    srv=''

    for s in $cfg_services0 $cfg_services1 $cfg_services2; do
        srv="$s $srv"
    done

    for s in $srv; do
        . /etc/rc.d/$s
        stop
    done

    umount -r /dev/pts /dev/shm /sys / /proc
}

service()
{
    . /etc/rc.d/"$1"

    case "$2" in
        start)
            start
            ;;
        stop)
            stop
            ;;
        restart)
            stop
            sleep 4
            start
            ;;
        *)
            echo "Usage: $0 <service> [start,stop,restart]"
            exit 1
            ;;
    esac
}


case "$1" in
    sysinit)
        sysinit
        ;;
    syshalt)
        syshalt
        ;;
    *)
        service "$1" "$2"
        ;;
esac