#!/bin/bash
# 20240123

# Function to execute a command with sudo
function sudo_execute() {
    echo terminal12 | su -c "$@" root
}

# Logger function
function log() {
    echo "$(date +"%Y-%m-%d %H:%M:%S") $1" >> "$DN/log/add/start.log"
}

logger -t run "Запуск" 

xset dpms 0 0 0
xset -dpms
xset s off
xhost +

DN=$(dirname "$0")
JAVAPATH="$DN/jre/bin"

mkdir -p "$DN/log/add" > /dev/null 2>&1
mkdir -p "$DN/java_dump" > /dev/null 2>&1
echo 'groups:' $(groups) >> "$DN/log/add/start.log"

#rm ~/.mozilla/firefox/*/sessionstore.{bak,js}
#firefox "$DN/v1.html"
#
#exit 0

if [ -f $DN/bin/dmidecode ];then
    /bin/bash $DN/bin/dmidecode $DN
fi

$DN/COFFEE_MACHINE/cm_stop

# Set permissions recursively
function set_permissions() {
    sudo_execute "chmod -R 775 $1/*"
    sudo_execute "chown -R terminal:terminal $1/*"
}

# Set permissions for the current directory and subdirectories
set_permissions "$DN"

# Clean up old files in java_dump directory
cleaned_files=$(find "$DN/java_dump" -type f -mtime +90 -exec rm {} \; -print)
[ -n "$cleaned_files" ] && log "Cleaned old files in java_dump directory: $cleaned_files"

if [ -f "$DN/jre/lib/rt.jar" ]; then
    CMD="$JAVAPATH/java"
else
    CMD="java"
fi

while true; do
        if [ -z "$(ps ax | grep java | grep ru.softlogic.app.Main)" -a -z "$(ps ax | grep java | grep ru.softlogic.configurator)" ]; then
		PARAMS=""
                CLASSPATH=$DN
                for jar in $(ls $DN/{lib,ext,ext/drivers}/*.jar); do
                        CLASSPATH=$CLASSPATH:$jar
                done

		if [ -f $DN/java.properties ]; then
		    for line in `cat $DN/java.properties`
		    do
		        if [ "x$line" != "x" ];then
		            PARAMS="-D$line $PARAMS"
		        fi
		    done
		fi

		if [ -f /home/terminal/atm/configuration.xml ]; then
		    # start coffee software
		    $DN/COFFEE_MACHINE/CMCSys.sh & $DN/COFFEE_MACHINE/cm_start &
		fi

		uptime >> "$DN/log/add/start.log"
                $CMD -cp $CLASSPATH -Djava.library.path=$DN/jni -Dterminal.dir=$DN $PARAMS -Xmx256m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=$DN/java_dump ru.softlogic.app.Main
                retval="$?"
		echo "`date +%H:%M:%S` QUIT $retval" >> $DN/log/add/start.log
		$DN/COFFEE_MACHINE/cm_stop

                if [ "$retval" == "15" ]; then
                        break
                elif [ "$retval" == "16" ]; then
                        $DN/configure.sh
                elif [ "$retval" == "17" ]; then
                        $CMD -cp $CLASSPATH  -Dterminal.dir=$DN $PARAMS ru.softlogic.app.UpdateMain
			$DN/run.sh &
			break
		elif [ "$retval" == "20" ]; then
			sudo /sbin/reboot
                else
                        sleep 20
                fi
        else
                sleep 20
        fi
done
