#!/bin/bash
#
# /etc/init.d/isu  --  script to start and stop isu.

export PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin

function exec_autostart()
{
    for AUTOSTART_PATH in $AUTOSTART_PATHS
    do
        pushd $AUTOSTART_PATH > /dev/null 2>&1
        if [ $(pwd) == $AUTOSTART_PATH ]
        then
            FILES=$(find . -name autostart.sh)
            for FILE in $FILES ; do
                echo $FILE $*
                sh $FILE $*
            done
            popd > /dev/null 2>&1
        fi
    done
    return 0
}

function wait_isu_stop()
{
    ATTEMPT=0
    while pidof Isu
    do
        let "ATTEMPT+=1"
        [ $ATTEMPT -gt 10 ] && break
        sleep 1
    done
}

test -x /acterna/release/bin/Isu || exit 0
source /etc/platform.conf

case "$1" in
    start)
        echo -n "Starting Instrument Setup: Isu"
        #removing mountdir in case of bad reboot
        rm -fr /user/bluetooth-inbox
        rm -fr /user/cloud-storage

        #we need to wait for the hwscan to complete
        if [ -e /etc/init.d/hwscan ]
        then
            /etc/init.d/hwscan wait_completion
        fi

        exec_autostart

        export DISPLAY=:0.0
        export QT_NO_GLIB=1
        MB=$(pidof matchbox-window-manager)
        if [ $? == 0 ]
        then
            export $(cat /proc/$MB/environ | tr '\0' '\n' | grep DBUS_SESSION)
        fi
        if [ -e /sys/platform/fb/splash_anim ]
        then
            echo 0 > /sys/platform/fb/splash_anim
        fi

        # If start+setup or file+sertup pushed, try to run Upgrade from DHCP
        if [ -d /sys/platform/keyboard ]
        then
            KEYCODE=$(printf "0x%x"  $(( $(cat /sys/platform/keyboard/ctrl) & 0x0FC0 )) )

            if [ $KEYCODE == "0xa40" -o $KEYCODE == "0xa80" ]
            then
                echo -e "\e[0;31m@@@@@@@@ START UPGRADE FROM DHCP @@@@@@@@@\e[0m"
                touch /var/volatile/upgrade_from_dhcp
            fi
        fi

        # Set group mask for all file create by Isu and Childs
        umask 0002
        chmod g+w /user/disk
        chgrp user /user/disk

        if [ -f /proc/device-tree/board/rescue-mode ] && [ "$(tr -d '\0' </proc/device-tree/board/rescue-mode)" == "yes" ] ;
        then
            logger -p user.emerg "Mode rescue active"
            start-stop-daemon --start --quiet --background --exec sg -- user -c "/acterna/release/bin/Isu INIT"
        else
            start-stop-daemon --start --quiet --background --exec sg -- user -c "/acterna/release/bin/Isu -pidfile /var/run/isu.pid"
        fi


        echo "."
        ;;
    stop)
        echo -n "Stopping Instrument Setup: Isu"
        start-stop-daemon --stop --retry TERM/20/KILL/5 --quiet --exec /acterna/release/bin/Isu
        wait_isu_stop
        echo "."
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    *)
        echo "Usage: /etc/init.d/isu {start|stop|restart}"
        exit 1
        ;;
esac

exit 0
