#!/bin/bash

export POST_CMD_FILE=/var/lock/marinara.postcmd
START_LOCKFILE=/opt/ssgnavigation/locius/var/graphic.json
LOCKFILE=/var/lock/marinara.lock
LOGDIR=$HOME/.marinara_logs
MAINTENANCE=/opt/ssgnavigation/locius/bin/ssg-maintenance
ECS=/opt/ssgnavigation/locius/bin/ssg_ecs
REPORT_PREPARE=/opt/ssgnavigation/marinara/makereport
REPORT_APP=/opt/ssgnavigation/marinara/ReportApp
SQUISH=$HOME/qa/squish/bin/squishserver
ALTERUSER=/opt/ssgnavigation/locius/sbin/alter_user.sh
NSR_ENV=/opt/ssgnavigation/locius/share/nsr_env.sh

#setxkbmap -rules xorg -model cp105 -layout "us,ru" -option "grp:alt_shift_toggle"

[ -r "$NSR_ENV" ] || setxkbmap us,ru

goodix_rotate=/opt/ssgnavigation/locius/sbin/goodix_rotate.sh
[ -x "$goodix_rotate" ] && $goodix_rotate

run_ecs()
{
#export QT_DEBUG_PLUGINS=1

# чтобы включить вывод в лог, уберите в следующей строке знак '#'
    $ECS #>> ${LOGDIR}/console_$(date +'%Y%m%d_%H%M%S').log 2>&1
    case "$?" in
        0|162) xterm ;;
        1|163) sudo /sbin/shutdown -r now ;;
        2|164) sudo /sbin/shutdown -h now ;;
        3|165) 
            xterm -e sudo "$MAINTENANCE" update
            sudo /sbin/shutdown -r now
            ;;
        4|166)
            xterm -e sudo "$MAINTENANCE" screen_test
            ;;
        *) ;;
    esac
}

do_start()
{
    if [ ! -f $START_LOCKFILE ]; then
        [ -x $ALTERUSER ] && sudo $ALTERUSER && sudo $MAINTENANCE start
    fi
    sudo $MAINTENANCE prestart

    [ -f $START_LOCKFILE ] && run_ecs || xterm
}


run_report()
{
    sudo $MAINTENANCE report
    case "$?" in
	1)
	sudo /sbin/shutdown -r now
        ;;
	2)
        sudo /sbin/shutdown -h now
        ;;
        *)
        ;;
    esac
}

# noblank
xset s -dpms
xset s off
xset s noblank
xhost +local:*

# disable bell
xset b 0 0

# exec xprofile as user if exists:
monit_setup=/opt/ssgnavigation/locius/var/xprofile
[ -f "${monit_setup}" ] && . $monit_setup

# exec board.setup as user if exists:
board_setup=/usr/local/sbin/board.setup
[ -x "${board_setup}" ] && $board_setup

# exec nsr env file if exists:
[ -f "${NSR_ENV}" ] && . $NSR_ENV

exec /usr/bin/dwm.web &

keylogger=/opt/ssgnavigation/locius/sbin/ssg_keylogger
[ -x "${keylogger}" ] && exec $keylogger &


mkdir -p "${LOGDIR}"

while true; do
    counter=4
    while [ $counter -gt 0 ]; do
	counter=$(( $counter - 1 ))
	if [ -x "${SQUISH}" ]; then
	    "${SQUISH}"
	    sudo /sbin/shutdown -r now
	else
	    do_start
	fi
    done
    run_report
done
