#!/bin/sh
### BEGIN INIT INFO
# Provides:          controlaula
# Required-Start:    $local_fs $remote_fs hostname
# Required-Stop:     $local_fs $remote_fs
# Should-Start:      avahi
# Should-Stop:       avahi
# Default-Start:     2 3 4 5
# Default-Stop:      1
# Short-Description: Controlaula root daemon
# Description:       Debian init script for Controlaula root monitoring daemon
### END INIT INFO
#
# Author:	José L. Redrejo Rodríguez <jredrejo at debian.org>
#


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

rundir=/var/run 
pidfile=$rundir/sirvecole.pid 
logfile=/var/log/controlaula.log
application=/usr/bin/sirvecole.py
twistd=/usr/bin/twistd

. /lib/lsb/init-functions

test -x $twistd || exit 0
test -r $application || exit 0

# return true if at least one pid is alive
alive()
{
    if [ -z "$*" ]; then
	return 1
    fi
    for i in $*; do
	if kill -0 $i 2> /dev/null; then
	    return 0
	fi
    done

    return 1
}

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
        if  grep  -qs "nfs" /etc/mtab 
        then    
                root_write_method="bind_mounts"
	  	bind_mounts
        fi  
 
  	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	
}

bind_mounts () {

    test -z "$tmpfs_dir" && tmpfs_dir=/var/lib/ltsp-client-setup
    rw_dirs="/var/lib/dbus /etc/avahi/services /var/cache/hald" 
    bindfiles="/etc/passwd /etc/group /etc/sirvecole"
    copy_dirs="/home /var/cache/ltsp-localapps"
   
    
    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

    # mount one file on top of another
    for f in $bindfiles ; do
        if [ -e "$f" ]; then
            mkdir -p "$(dirname $tmpfs_dir/$f)"
            cp $f $tmpfs_dir/$f
            mount --bind $tmpfs_dir/$f $f
        else
            echo "WARNING: $f does not exist"
        fi
    done
    
}

case "$1" in
    start)
	log_daemon_msg "Starting ControlAula"	
	[ ! -f $logfile ] && touch $logfile
	# Make cache files readable
    start_dependent_services
	umask 022
	start-stop-daemon --start --quiet --exec $twistd -- \
            --pidfile=$pidfile  --python $application	--rundir=$rundir  \
	    --logfile=$logfile  --reactor=glib2 	--no_save
	log_end_msg $?
    ;;

    stop)
	log_daemon_msg "Stopping ControlAula"
	start-stop-daemon --stop --quiet --pidfile $pidfile
	#
	# Continue stopping until daemon finished or time over
	#
	count=0
	pid=$(cat $pidfile 2>/dev/null)
	while alive $pid; do
		if [ $count -gt 20 ]; then
			log_progress_msg " aborted"
			break;
		elif [ $count = 1 ]; then
			log_progress_msg " [wait $count"
		elif [ $count -gt 1 ]; then
			log_progress_msg " $count"
		fi
		count=$(expr $count + 1)
		sleep 1
		start-stop-daemon --stop --quiet --pidfile $pidfile
	done
	if [ $count -gt 1 ]; then
		log_progress_msg "]"
	fi
	log_end_msg $?
    ;;

    restart)
	$0 stop
	$0 start
    ;;
    
    force-reload)
        $0 restart
    ;;

    *)
	log_success_msg "Usage: /etc/init.d/controlaula {start|stop|restart|force-reload}"
	exit 1
    ;;
esac

exit 0
