#!/bin/sh
export PATH=/opt/lnxall_app/bin:/opt/lnxall_app/sbin:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin
PLATSPEC=/opt/lnxall_app/platspec
UPDATE_LOGO=0

check_command() {
	command -v "$1" >/dev/null 2>&1 || {
		echo "Error, missing command: $1"
		exit 1
	}
}
check_command ffmpeg
check_command dumpimage
check_command resource_tool
check_command mkimage
check_command dtc
[ -f "/usr/share/kernel_logo/boot.img" ] || {
	echo "Error, missing file /usr/share/kernel_logo/boot.img"
	exit 1
}

rm -r -v -f /etc/splash.d ; ln -s -v -n -f /opt/lnxall_app/etc/splash.d /etc/splash.d
[ -L /etc/splash.d ] && [ -e /etc/splash.d ] || {
    echo "Error, /etc/splash.d symlink is invalid"
    exit 2
}

cp -v -f $PLATSPEC/boot-splash.service /lib/systemd/system
[ $? -ne 0 ] && exit 3

# generate background/logo BMP onlyif don't exist
if [ ! -f /etc/splash.d/background.bmp ] ; then
	ffmpeg -hide_banner -loglevel error -nostats -y \
		-i $PLATSPEC/background.jpeg \
		-pix_fmt bgr24 /etc/splash.d/background.bmp \
	|| exit 4
fi
if [ ! -f /etc/splash.d/logo.bmp ] ; then
	ffmpeg -hide_banner -loglevel error -nostats -y \
		-i $PLATSPEC/logo.jpeg \
		-vf "scale=500:500:force_original_aspect_ratio=decrease,colorkey=black:0.1:0.0,format=bgra,vflip" \
		-pix_fmt bgra /etc/splash.d/logo.bmp \
	&& python3 -c 'import struct; p="/etc/splash.d/logo.bmp"; f=open(p,"r+b"); f.seek(22); h=struct.unpack("<i",f.read(4))[0]; f.seek(22); f.write(struct.pack("<i",-abs(h))); f.close()' \
	|| exit 5
	UPDATE_LOGO=1
fi
if [ "$UPDATE_LOGO" -eq 1 ] ; then
	rk3568_change_bootlogo /etc/splash.d/logo.bmp || exit 6
fi

# remove old logo config
if [ -f /etc/lightdm/lightdm.conf ] ; then
	sed -i '/^[[:space:]]*autologin-session[[:space:]]*=[[:space:]]*logo-session[[:space:]]*$/d' \
		/etc/lightdm/lightdm.conf
fi
rm -v -f /home/linaro/.config/autostart/logo-session.desktop

systemctl daemon-reload
systemctl enable boot-splash.service

exit 0
