#!/bin/sh
#
# Starts/stops Cicada processes.
#

export QT_DBL_CLICK_DIST=100

# events used by the EventSync mechanism
STARTUP_EVENTS="visibleInitDone supermanReady storageManagerReady rmanReady soundDaemonReady batteryMgrReady"

NOREBOOT_FILE=/tmp/cicada_no_reboot_on_fail
SHUTDOWN_FILE=/tmp/cicada_shutting_down
WARM_RESTART_FILE=/tmp/cicada_warm_restart
SUPERMAN_READ_EEPROM_FILE=/tmp/superman_read_eeprom
COREFILE_DIR=/var/log/core_dumps

# see if we are running in rescue mode
if grep -q -E 'cicada_rescue|cicada_fallback|cicada_desperate' /proc/cmdline
then
    RESCUE=true
else
    RESCUE=false
fi

# see if we are running in factory bring-up mode (i.e. the mode where the
# EEPROM is blank or corrupt, and we're booting off a usb flash drive)
if grep -q cicada_factory /proc/cmdline
then
    FACTORY=true
else
    FACTORY=false
fi

HWTYPE_DIR=/sys/devices/platform/board-id
HWTYPE_ID=99
UIAPP_NAME=no-ui
if [ -f $HWTYPE_DIR/hw_type ] ; then
    HWTYPE_ID=`cat $HWTYPE_DIR/hw_type`
    if [ "$HWTYPE_ID" = 0 ] ; then
        UIAPP_NAME=ui
    elif [ "$HWTYPE_ID" = 1 ] ; then
        UIAPP_NAME=remote-ui
    fi
fi
UIAPP=/opt/cicada/bin/$UIAPP_NAME

# return true if we have a display (i.e. this is a main versus a remote)
have_display() {
    [ "$HWTYPE_ID" = 0 ]
}

# Invoke splash_write if we have a display.
# Also retry on error, in case the psplash daemon has just been started and
# isn't ready for commands yet.
splash_write() {
    if have_display ; then
        local tries=3
        while ! psplash-write "$1" 2> /dev/null && [ $tries -gt 0 ]; do
            usleep 100000
            let "tries -= 1"
        done
    fi
}

start() {
    rm -f $SHUTDOWN_FILE
    rm -f $WARM_RESTART_FILE
    rm -f $SUPERMAN_READ_EEPROM_FILE
    rm -f $COREFILE_DIR/*

    splash_write "QUIT" 2> /dev/null

    # Initialize EventSync directories
    for i in $STARTUP_EVENTS; do
        rm -rf /tmp/cicadaEvents/$i;
        mkdir -p /tmp/cicadaEvents/$i;
    done

    # Create storage manager dirs on eMMC
    mkdir -p /media/mmcblk2p7/shared
    mkdir -p /media/mmcblk2p7/userdata

    # generate CWIZ sym links
    # WBN - do this at root filesystem build time instead of runtime
    echo -n "Generating CWIZ links: "
    mkdir -p /var/cwiz
    /opt/cicada/bin/cwiz --install
    echo "OK"

    /usr/sbin/logrotate /etc/logrotate.conf

    /usr/sbin/start-stop-daemon -S -v --exec /opt/cicada/bin/loggerd -- -b

    # check sysconf bits for whether we should reboot on assert, touch file
    SYSCONFBITS=`/var/cwiz/sysconf --raw 2> /dev/null`
    if [ -z "$SYSCONFBITS" ] ; then
        SYSCONFBITS=0
    fi
    if [ $(($SYSCONFBITS & 1)) -ne 0 -o "$RESCUE" = true -o "$FACTORY" = true ] ; then
        touch $NOREBOOT_FILE
    fi

    # enable core dumps if "siren on assert" is set
    if [ $(($SYSCONFBITS & 1)) -ne 0 ] ; then

        # max size of core dumps (defaults to 0, i.e. disabled)
        ulimit -c 50000000

        # where to put core files
        mkdir -p $COREFILE_DIR

        # tell the kernel what to name core files: core-<executable-name>
        echo -n $COREFILE_DIR/core-%e > /proc/sys/kernel/core_pattern
    fi

    /usr/sbin/start-stop-daemon -S -v --background --exec /opt/cicada/bin/sound-daemon

    /usr/sbin/start-stop-daemon -S -v --background --exec /opt/cicada/bin/warnerr-monitor

    if [ "$RESCUE" = true ] ; then
        SUPERMAN_RESCUE=--rescue
    fi
    /usr/sbin/start-stop-daemon -S -v --exec /opt/cicada/bin/superman -- --hwmgr $SUPERMAN_RESCUE

    /usr/sbin/start-stop-daemon -S -v --background --exec /opt/cicada/bin/battery

    if [ "$RESCUE" = false -a "$FACTORY" = false ] ; then
        # MAN-2013. Specify directory for sqlite3 temporary transaction files
        # otherwise /var/tmp will be chosen automatically which is too small.
        # https://www.sqlite.org/tempfiles.html
        export SQLITE_TMPDIR=/tmp
        /usr/sbin/start-stop-daemon -S -v --background --exec /opt/cicada/bin/sm
        if have_display ; then
            /usr/sbin/start-stop-daemon -S -v --background --exec /opt/cicada/bin/usbwifimgr
            /usr/sbin/start-stop-daemon -S -v --background --exec /opt/cicada/bin/lopez
        fi

        if [ $(($SYSCONFBITS & 0x800)) -ne 0 -o "$1" = "vnc" ] ; then
            VNCAPP=/opt/cicada/bin/x11vnc-helper
            /usr/sbin/start-stop-daemon -S --background -v --exec $VNCAPP
        fi
        export QT_QPA_PLATFORM=fnetlinuxfb:mmsize=87x116:rotation=90:pxp=/dev/pxp_device
        export QT_QPA_EVDEV_KEYBOARD_PARAMETERS=evdevkeyboard:/dev/fifo.ui-keys
        export QT_PAN_TOUCHPOINTS=1

        if have_display ; then
            UIAPP_ARGS="-platforms $QT_QPA_PLATFORM"
        else
            UIAPP_ARGS=
        fi

        /usr/sbin/start-stop-daemon -S --background -v --exec $UIAPP -- $UIAPP_ARGS

#       if have_display ; then
#           # allow meas processes to be spawned on main units w/o a display
#           if [ ! -e /dev/ts ] ; then
#               echo "No touchscreen found, faking visibleInitDone signal" > /dev/console
#               /opt/cicada/bin/cwiz signalevent visibleInitDone 2> /dev/null
#           fi
#       fi

        /usr/sbin/start-stop-daemon -S -v -N -20 --background --exec /opt/cicada/bin/rman
    fi

    # issue warnerr if lantis module present
    if [ -f /var/tmp/lantisModuleDetected ]; then
        /opt/cicada/bin/cwiz warnerr 6 "versiv v2 does not support lantis"
        rm -f /var/tmp/lantisModuleDetected
    fi

#   # inhibit kernel 10-minute screen blanking
#   if [ "$RESCUE" = true -o "$FACTORY" = true ] ; then
#       /opt/cicada/bin/cwiz noblank
#    fi

    # run optional developer-only commands (but only if not running
    # in rescue mode)
    DEV_INIT_FILE=/var/cicada/developer-init
    [ $RESCUE = false ] && [ -f $DEV_INIT_FILE ] && . $DEV_INIT_FILE

    return 0
}

stopproc() {
    # send a TERM signal, wait $2 seconds for the process to exit.  If it
    # doesn't exit, send it a KILL (-9) signal.
    /usr/sbin/start-stop-daemon -K -n $1 -v -R TERM/$2/KILL
}

stopall() {

    touch $SHUTDOWN_FILE

    /var/cwiz/soundshutdown 2> /dev/null

    stopproc x11vnc-helper $1
    stopproc $UIAPP_NAME $1

    # now that UI is stopped, start psplash to display logo and shutdown
    # progress
    if have_display ; then
        psplash -n -a 270 2> /dev/null &
    fi

    splash_write "MSG Shutting down, please wait..."

    splash_write "PROGRESS 5" 2> /dev/null

    stopproc measfib-otdr $1
    stopproc measfib-ll $1
    stopproc measfib-dfu $1

    splash_write "PROGRESS 15" 2> /dev/null

    stopproc meascop $1
    stopproc rman $1

    splash_write "PROGRESS 25" 2> /dev/null

    stopproc lopez $1
    stopproc usbwifimgr $1

    splash_write "PROGRESS 35" 2> /dev/null

    stopproc sm $1
    stopproc battery $1

    splash_write "PROGRESS 45" 2> /dev/null

    stopproc superman $1
    stopproc warnerr-monitor $1

    splash_write "PROGRESS 55" 2> /dev/null

    stopproc sound-daemon $1
    stopproc loggerd $1

    splash_write "PROGRESS 65" 2> /dev/null
}

restart() {
    # warm restart initiated from shell
    touch $WARM_RESTART_FILE
    stopall 25
    splash_write "QUIT" 2> /dev/null
    start $1
}

case "$1" in
    start)
        start 0
        ;;
    stop)
        stopall 25
        ;;
    quickstop)
        # warm restart initiated from make user-install
        touch $WARM_RESTART_FILE
        stopall 3
        ;;
    restart|reload)
        restart $2
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?

