#!/bin/sh
### BEGIN INIT INFO
# Provides:          ltsp-sirvecole
# Should-Start:      avahi-daemon
# Required-Start:    $local_fs $remote_fs dbus avahi
# Required-Stop:     $local_fs $remote_fs dbus avahi
# Default-Start:     2 3 4 5
# Default-Stop:      0  6
# Short-Description: Controlaula root daemon in a ltsp environment
# Description:       Debian init script for Controlaula root monitoring daemon when using ltsp
### END INIT INFO
#
# Author:	José L. Redrejo Rodríguez <jredrejo at debian.org>
#

#set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/ltsp-sirvecole.gambas
PIDFILE=/var/run/ltsp-sirvecole.pid
DESC="ltsp-sirvecole"
NAME=ltsp-sirvecole



test -x $DAEMON || exit 0

. /lib/lsb/init-functions

if [ -r /etc/default/locale ]; then
  . /etc/default/locale
  export LANG LANGUAGE
fi

. /lib/lsb/init-functions


bind_mounts () {
	test -z "$tmpfs_dir" && tmpfs_dir=/var/lib/ltsp-client-setup
    rw_dirs="/var/lib/dbus /etc/avahi/services " 
    copy_dirs="/etc "
    
    for f in $rw_dirs ; do
    	touch "$f" 2> /dev/null || root_write_method="bind_mounts"
        if [ -e "$f" ]  &&  [ "$root_write_method" = "bind_mounts" ]; then
        	root_write_method=""
            mkdir -p $tmpfs_dir/$f
            mount --bind $tmpfs_dir/$f $f
        else
            echo "WARNING: $f does not exist or it's already writtable"
        fi
    done
    
    for d in $copy_dirs ; do   	
        touch "$d" 2> /dev/null || root_write_method="bind_mounts"
		if [ -d "$d" ] &&  [ "$root_write_method" = "bind_mounts" ]; then
			root_write_method=""
            cd $tmpfs_dir
            tar -cpf - $d 2> /dev/null | tar xpf -
            mount --bind $tmpfs_dir/$d $d
        else
            echo "WARNING: $d does not exist or it's already writtable"
        fi
    done
    
}



start_dependent_services()
{
	
  # Determine current runlevel
  r=$(/sbin/runlevel) || true
  r=${r#*\ }
  
  if [ "$r" = "unknown" ]; then #we're inside the ltsp chroot: mount needed dirs on tmpfs
  
  	bind_mounts 
  	sleep 1
  else
  	return
  fi
  services="dbus avahi-daemon"
  # Start the services in the correct order
  for i in $services ; do
    service=$(basename $i)
    service=${service#S??}
    invoke-rc.d $service start || true
  done	
}

do_start() {
    log_daemon_msg "Starting $DESC" "$NAME"
    start_dependent_services
    start-stop-daemon --start --startas $DAEMON --quiet --pidfile $PIDFILE
    log_end_msg $?
}

do_stop() {
    log_daemon_msg "Stopping $DESC" "$NAME"
    start-stop-daemon --stop --oknodo --quiet --pidfile $PIDFILE --startas $DAEMON
    log_end_msg $?
}

case "$1" in
  start)
    do_start
    ;;
    
  stop)
    do_stop
    ;;

  restart|reload|force-reload)
  do_stop
    sleep 2
  do_start
    ;;
    
  *)
    N=/etc/init.d/$NAME
    log_success_msg "Usage: $N {start|stop|restart|force-reload}" >&2
    exit 1
    ;;
esac

exit 0
