#!/bin/ash

# copyright 2004 vagrant@freegeek.org, distributed under the terms of the
# GNU General Public License version 2 or any later version.

# TODO split X related configuration into sourced file?

case "$1" in
  start) ;;
  stop) ;;
  restart) ;;
  force-reload) ;;
esac

# FIXME this is a crude workaround.  for some reason $runlevel is already set.
unset runlevel

if [ -r /etc/lessdisks/server.config ]; then
  . /etc/lessdisks/server.config 
fi

if [ -r /etc/lessdisks/x.config ]; then
  . /etc/lessdisks/x.config
fi

if [ -z "$rw" ]; then
  rw="/var/state/lessdisks"
fi

if [ -r "$rw/etc/config" ]; then
  . "$rw/etc/config"
fi

if [ -z "$hostname" ]; then
  hostname=$(cat $rw/etc/hostname)
fi

if [ -z "$hostname" ]; then
  hostname=default
fi

if [ -r /etc/lessdisks/terminals/$hostname ]; then
  . /etc/lessdisks/terminals/$hostname
fi

if [ -n "$session" ]; then
  if [ -x /etc/lessdisks/sessions.d/$session ]; then
    /etc/lessdisks/sessions.d/$session &
  elif [ -n "$(which $session)" ] || [ -x "$session" ]; then
    $session &
  else
    echo "WARNING: no command found for $session"
    echo "add script in /etc/lessdisks/sessions.d"
    echo "or install appropriate package"
  fi
fi

if [ -z "$runlevel" ]; then
  if [ "true" = "$auto_start_x" ] && [ -n "$default_x_runlevel" ]; then
    runlevel="$default_x_runlevel"
  elif [ -n "$default_runlevel" ]; then
    runlevel="$default_runlevel"
  else
    echo "runlevel not set, assuming runlevel 2"
    runlevel=2
  fi
fi

case $runlevel in
  2) exit 0 ;;
  3|4|5) echo "switching to runlevel $runlevel"
    telinit $runlevel
    exit 0 ;;
  *) echo "WARNING: runlevel set to $runlevel"
    echo "change runlevel value in /etc/lessdisks/terminals/$hostname to 2,3,4 or 5"
    exit 1 ;;
esac
