#!/bin/sh
# Timesys sysvinit 
# This init supports a simplified flat /etc/init.d structure similar to busybox
# init (which does not support runlevels).  Also supported is proper runlevel
# definitions following the following structure:
# etc/rc[runlevel].d/
#                   SXX-foo
#                   KXX-bar
# rc.local in /etc/init.d is always run last (or first on shutdown/restart)

# env
export PATH=/bin:/sbin:/usr/bin:/usr/sbin
runlevel=$RUNLEVEL
[ "$1" != "" ] && runlevel=$1
if [ "$runlevel" = "" ]
then
  echo "Usage: $0 <runlevel>" >&2
  exit 1
fi
previous=$PREVLEVEL
[ "$previous" = "" ] && previous=N
export runlevel previous


# if we have run levels
if [ -d /etc/rc$runlevel.d ]
then

  case $runlevel in
    6|0)
      # stop on rc.local
      if [ -x /etc/init.d/rc.local ]; then
        /etc/init.d/rc.local stop
      fi
    ;; 
  esac

  # run all kill scripts for this run level
  if ls /etc/rc$runlevel.d/K* > /dev/null 2>&1; then
    for stopscript in /etc/rc$runlevel.d/K*
    do
      if [ -x $stopscript ]; then
        $stopscript stop
      fi
    done
  fi

  # run start scripts for this run level
  if ls /etc/rc$runlevel.d/S* > /dev/null 2>&1; then
    for startscript in /etc/rc$runlevel.d/S*
    do
      if [ -x $startscript ]; then
        $startscript start
      fi
    done
  fi

  # what to do at the end
  case $runlevel in
    6)
      /etc/init.d/rcK
      reboot -f
    ;;
    0)
      /etc/init.d/rcK
      halt -f
    ;;
    *)
    # compatibility, if we still have start scripts in /etc/init.d
    if ls /etc/init.d/S* > /dev/null 2>&1; then
      for startscript in /etc/init.d/S*
      do
        if [ -x $startscript ]
        then
          $startscript start
        fi
      done
    fi

    if [ -x /etc/init.d/rc.local ]; then
      /etc/init.d/rc.local start
    fi
    ;;
  esac

else
# otherwise, this is a simple, flat init directory structure

  case $runlevel in
    6|0)

      # stop on rc.local
      if [ -x /etc/init.d/rc.local ]; then
        /etc/init.d/rc.local stop
      fi

      # run kill scripts
      if ls /etc/init.d/K* > /dev/null 2>&1; then
        for stopscript in /etc/init.d/K*
        do
          if [ -x $stopscript ]
          then
            $stopscript stop
          fi
        done
      fi

      # final rcK
      /etc/init.d/rcK

      case $runlevel in
        6)
          reboot -f
        ;;
        0)
          halt -f
        ;;
      esac
    ;;
    *)
      # all other runlevels
      if ls /etc/init.d/S* > /dev/null 2>&1; then
        for startscript in /etc/init.d/S*
        do
          if [ -x $startscript ]
          then
            $startscript start
          fi
        done
      fi

      # rc.local last
      if [ -x /etc/init.d/rc.local ]; then
        /etc/init.d/rc.local start
      fi

    ;;
  esac
  
fi
