#!/bin/bash
#
# Initialize andromeda on first boot if it exists
# as CI fails to initalize it

set -e

[ -f "/usr/bin/andromeda" ] && ANDROMEDA=true

if [ "${ANDROMEDA}" == "true" ]; then
	# andromeda needs this to init
	while [ ! -e "/dev/ashmem" ]; do
		echo "Waiting for /dev/ashmem to appear..."
		sleep 1
	done

	# andromeda also needs this to init
	while [ ! -e "/dev/anbox-binder" ]; do
		echo "Waiting for /dev/anbox-binder to appear..."
		sleep 1
	done

	# this one comes from andromeda itself, needed to detect if device is halium or mainline
	if [ -f "/vendor/build.prop" ]; then
		vndk_version=$(grep '^ro.vndk.version=' /vendor/build.prop | cut -d'=' -f2)

		if [ -z "$vndk_version" ]; then
			echo "ro.vndk.version not found"
			exit 0
		fi

		if [ "$vndk_version" -lt 19 ]; then
			echo "Unsupported VNDK version: $vndk_version"
			exit 0
		fi
	else
		echo "build.prop does not exist"
		exit 0
	fi

	sleep 10

	# Andromeda checks for IAllocator to detect which gralloc it should use, without that it initializes too early and chooses swiftshader
	binder-wait android.hardware.graphics.allocator@4.0::IAllocator/default

	if which -s andromeda; then
		andromeda init -f || true
	fi

	# now restart all services
	if [ -f "/usr/lib/systemd/system/andromeda-container.service" ]; then
		systemctl restart andromeda-container || true
		sleep 1
        fi

	if [ -f "/usr/lib/systemd/system/andromeda-sensors.service" ]; then
		systemctl restart andromeda-sensors || true
		sleep 1
	fi

	if [ -f "/usr/lib/systemd/system/andromeda-notification-server.service" ]; then
		systemctl restart andromeda-notification-server.service || true
		sleep 1
	fi

	if [ -f "/usr/lib/systemd/system/andromeda-statechange-server.service" ]; then
		systemctl restart andromeda-statechange-server.service || true
		sleep 1
	fi
fi
