#!/bin/sh
#
# Copyright (C) 2004-2005 Nokia Corporation.
#
# Author(s): Kimmo Hmlinen <kimmo.hamalainen@nokia.com>

DIR=/etc/osso-af-init

AF_DEFS=$DIR/af-defines.sh
source $AF_DEFS || exit 2

case "$1" in
start)  START=TRUE
        ;;
stop)   START=FALSE
        ;;
restart)
        echo "$0: not implemented"
        exit 1
        ;;
force-reload)
        echo "$0: not implemented"
        exit 1
        ;;
*)      echo "Usage: $0 {start|stop}"
        exit 1
        ;;
esac


if [ $START = TRUE ]; then
  # GConf daemon (probably started already by D-BUS)
  source $DIR/gconf-daemon.sh start

  # Must be before D-BUS session bus is started!
  source $DIR/osso-gtk.defs

  # opera needs some definitions
  if [ -f $DIR/browser.defs ]; then
    source $DIR/browser.defs
  fi
  # LD_PRELOAD script (only for the session bus environment)
  LDPRELOADSCRIPT=/usr/bin/connectivity_preload.sh
  if [ -f $LDPRELOADSCRIPT ]; then
    source $LDPRELOADSCRIPT
  fi
  source $DIR/dbus-sessionbus.sh start
  unset LD_PRELOAD

  # Wait until X is ready
  INC=1
  while [ ! -e /tmp/.X11-unix/X0 ]; do
    if [ $INC -gt 20 ]; then
      echo "$0: Error, X server did not start"
      exit 2
    fi
    sleep 1
    INC=`expr $INC + 1`
  done

  source $DIR/sapwood-server.sh start

  if [ -f $DIR/matchbox.defs ]; then
    source $DIR/matchbox.defs
  fi
  source $DIR/matchbox.sh start

  # wait until system D-BUS is ready (some stuff started by init
  # after us assume it is running)
  /usr/sbin/waitdbus system
  if [ $? -gt 0 ]; then
    echo "$0: Error, the D-BUS system bus did not start"
    exit 2
  fi

  # media-server is only started here if we go directly to ACTDEAD
  DSME_STATE=`/usr/sbin/bootstate`
  if [ "x$DSME_STATE" = "xACTDEAD" ]; then
    # LD_PRELOAD script (only for media-server)
    LDPRELOADSCRIPT=/usr/bin/connectivity_preload.sh
    if [ -f $LDPRELOADSCRIPT ]; then
      source $LDPRELOADSCRIPT
    fi
    if [ -x $DIR/osso-media-server.sh ]; then
      $DIR/osso-media-server.sh start
    fi
    unset LD_PRELOAD
  fi
else
  $DIR/osso-media-server.sh stop
  source $DIR/matchbox.sh stop
  source $DIR/sapwood-server.sh stop
  source $DIR/dbus-sessionbus.sh stop
  source $DIR/gconf-daemon.sh stop
fi
