#!/bin/sh
#
# applicationManager:   The Application Manager service
#
# chkconfig: 345 40 61
# description:  This is a daemon that manages ICT Applications.
#
# processname: applicationManager
# pidfile: /var/run/ict/applicationManager.pid
#
### BEGIN INIT INFO
# Provides: applicationManager
# Required-Start: $syslog $local_fs
# Required-Stop: $syslog $local_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: The Application Manager
# Description: This is a daemon which broadcasts notifications of system
#  events and other messages. See http://www.freedesktop.org/software/dbus
### END INIT INFO



. /etc/init.d/rc.config

# so we can rearrange this easily
processdir=/usr/bin/ICTApplication
processname=ApplicationManager
servicename=ApplicationManager
pidfile=/var/run/applicationManager.pid
profiledir=/tmp/profile.d
datafile=$profiledir/applicationManager.sh
lockfile=/var/lock/subsys/$servicename
apacheservice="/usr/sbin/apachectl"
apachestartparams="-f /usr/share/ICTApplication/library/ICTouchAPI/Config/httpd.conf -k graceful"
apachelogpath="/var/log/apache2/logs/"
test_upgrade="/usr/sbin/upgd_status"
RETVAL=0
DIRECT_FB=1

[ ! -d "$profiledir" ] && mkdir -p $profiledir
start() {
    $test_upgrade > /dev/null 2>/dev/null
    [[ $? == 1 ]] && echo "Upgrade in progress: no application manager start" && return ;
    launch
}
move_db_path(){	
	old_path="/var/ICTApplication"
	new_path="/data/ICTApplication"
	if [[ -d $old_path && !  -L "$old_path" ]]; then
		# if old path is not a symlink (migration not done)
		: "Moving db path from $old_path to $new_path"
		for file in `find $old_path`
		do
			newFile=${file//var/data}
			if [[ -d $file && ! -d  $newFile ]]; then 
				: "Creating directory $newFile"
				mkdir $newFile
			else 
				if [[ ! -d $file && ! -f $newFile ]]; then
					# we pass thru a temp file because only a move in same partition is atomic
					: "Moving file $file"
					tmpFile="${newFile}.new"
					cp -fa $file $tmpFile
					mv $tmpFile ${newFile}
				fi 
			fi
		done
		: "Removing old db path"
		rm -rf $old_path
		
    	fi
	if [[ !  -L "$old_path" ]]; then
		: "Creating symlink with old db path"
		ln -s $new_path $old_path
	fi
}
launch() {
	move_db_path
    [ ! -d /Settings ] && mkdir /Settings
    chmod 755 /Settings
    [ ! -f /Settings/Trolltech.conf ] && touch /Settings/Trolltech.conf
    chmod 644 /Settings/Trolltech.conf

    [ -f $pidfile ] && [ -e /proc/$(cat $pidfile) ]  && return
    startapache

    [ -f /tmp/rpms_changes ] && DIRECT_FB=0;
    option="-qws $1"
    if [ $DIRECT_FB -eq 1 ]; then
        echo "Uses directFB"
        option="$option no_mouse"
        option="$option -display directfb"
        unset QWS_MOUSE_PROTO
    else
        export QWS_MOUSE_PROTO=tslib:/dev/input/event1
    fi

    $processdir/$processname ${option:-} --pidFile=$pidfile
    RETVAL=$?
    if [ $RETVAL -eq 0 ]; then
        touch $lockfile

        # prevent oom_killer to kill ApplicationManager
        echo -17 > /proc/`cat $pidfile`/oom_adj

        # prevent oom_killer to kill Platform
        echo -17 > /proc/`ps | grep Platform | grep -v grep | awk '{print $1}'`/oom_adj

	# favorize IctWebClient killed by oom_killer
	echo 15 > /proc/`ps | grep IctWebClient | grep -v grep | awk '{print $1}'`/oom_adj

        exit 0
    fi
    if [ $RETVAL -eq 1 ]; then
        echo "Warning: No PresentationReady event received" >&2;
        touch $lockfile
        exit 0
    fi
    if [ $RETVAL -eq 2 ]; then
        echo "Error: ApplicationManager isn't started" >&2;
        rm -f $lockfile
        rm -f $pidfile
        exit 1
    fi
}
startapache() {
    $test_upgrade > /dev/null 2>/dev/null
    [[ $? == "1" ]] && return;
    echo "Start Apache"
    [ ! -d $apachelogpath ] && mkdir -p $apachelogpath
    $apacheservice $apachestartparams > /dev/null 2>/dev/null
}

stopapache() {
    echo "Stop Apache"
    $apacheservice stop > /dev/null 2>/dev/null
}

debug() {
    echo "DEBUG MODE"
    launch --debug
}
stop() {
    ## we don't want to kill all the per-user $processname, we want
    ## to use the pid file *only*; because we use the fake nonexistent
    ## program name "$servicename" that should be safe-ish
    # killproc $servicename -TERM
    pid=`cat $pidfile`
    kill -TERM $pid 2>/dev/null
    RETVAL=$?
    if [ $RETVAL -eq 0 ]; then
        while [[ -d /proc/$pid/ ]]
        do
            usleep 1000
        done
        echo "ApplicationManager stopped"
        rm -f $lockfile 2>/dev/null
        rm -f $pidfile 2>/dev/null
        stopapache
    fi
}
reload() {
    kill -HUP `cat $pidfile`
}
# See how we were called.
case "$1" in
    start)
        start
        ;;
    launch)
        launch
        ;;
   debug)
        debug
        ;;
    stop)
       stop
        ;;
    move_db)
       move_db_path
        ;;
    status)
        if [ -f $pidfile -a -f $lockfile ]; then
            echo ApplicationManager running `cat $pidfile`
        else
            echo ApplicationManager stopped
        fi
        ;;
    restart)
        stop
        launch
        ;;
    condrestart)
        if [ -f $lockfile ]; then
            stop
            start
        fi
        ;;
    reload)
        reload
        ;;
    *)
        echo "Usage: $0 {start|debug|stop|status|restart|condrestart|reload}"
        ;;
esac

exit $RETVAL
