#!/bin/sh
#
# /lib/init/functions
#
# (C)opyright Teco a.s.
#
# 2021/07/01 Hosek Martin <hosek@tecomat.cz>
#

PBAR_REPEAT_NC="1"
PBAR_PORT_NC="8889"
PBAR_PIPE_NC="/tmp/pbarnc"

LOCK_FILE_DIR="/var/run"

lock_file_init()
{
    if [ "$1" ]; then
	LOCK_FILE="$1"
    else
	LOCK_FILE="${LOCK_FILE_DIR}/$(basename $0).pid"
    fi

    if [ ! -f "$LOCK_FILE" ]; then
	echo "$$ $2" > "$LOCK_FILE"
	return 1
    fi

    return 0
}

lock_file_pid()
{
    if [ -f "$LOCK_FILE" ]; then
	awk '{print $1}' ${LOCK_FILE}
    fi
}

lock_file_tfw()
{
    if [ -f "$LOCK_FILE" ]; then
	awk '{print $2}' ${LOCK_FILE}
    fi
}

lock_file_exit()
{
    local pid=`lock_file_pid`

    if [ -f "$LOCK_FILE" ]; then
	if [ "$pid" = "$$" ]; then
	    rm -f "$LOCK_FILE"
	    return 0
	fi
    fi

    return 1
}

getpids()
{
    local pids=""

    pids=`ps | awk -v psname="$1" '{if($4 ~ psname) printf("%d ", $1)}'`

    echo $pids
}

show_pbar()
{
    local PERCENT=""

    expr $2 \+ 1 >/dev/null 2>&1

    if [ $? = 0 ]; then
        PERCENT=$(($2 * 10))
    fi

    PIDS=`getpids "ncat"`

    if [ "$PIDS" -a -p "$PBAR_PIPE_NC" ]; then
	if [ "$PERCENT" ]; then
	    echo "{ \"progress\": ${PERCENT}, \"message\": \"${1}\", \"error\": \"${3}\" }" > "$PBAR_PIPE_NC"
	fi
    fi

    return $ret
}

get_disp_rot()
{
    if [ -r /etc/default/xserver ]; then
	. /etc/default/xserver
    fi

    local LOGO_ROTATION="$XSERVER_ROTATION"

    if [ ! "$LOGO_ROTATION" ]; then
	LOGO_ROTATION=`nanddump -o -b -l 4096 -f - /dev/mtd8 2>/dev/null | grep "logo_rotation" | sed s/"^.*="/""/`

	if [ ! "$LOGO_ROTATION" ]; then
	    LOGO_ROTATION="0"
	fi
    fi

    echo ""$LOGO_ROTATION""
}

fb_cur_disable()
{
    # Disable FB cursor
    echo -en '\e[?25l' >/dev/tty0
}
