#!/bin/sh

# Copyright (c) 2018 - 2023 Jolla Ltd.
#
# License: Jolla Proprietary

BASE_INSTALL_PATH="$(appsupport-config --base)"
source "$BASE_INSTALL_PATH/init/appsupport-common"
appsupport_init_source $1

if [ -z "$CONTAINER_SERVICE" ]; then
    CONTAINER_SERVICE="$(appsupport-config --name $CONFIG_INSTANCE)"
fi

if systemctl is-active --quiet $CONTAINER_SERVICE; then
    # Service already running, no need to start anything.
    exit 0
fi

CONTAINER_CONFIG_FILE="$(appsupport-config $CONFIG_INSTANCE --config)"

if [ -z "$ANDROID_DATA_ROOT" ]; then
    echo "appsupport-start: internal error, \$ANDROID_DATA_ROOT not defined!" >&2
    exit 32
fi

rm -rf $ANDROID_DATA/alien_boot_completed
rm -rf $ANDROID_DATA/alien_restart_requested

START_PID=$$

(

while [ "$(appsupport-attach $CONFIG_INSTANCE /system/bin/getprop hwservicemanager.ready)" != "true" ]; do
    echo "Waiting for hwservicemanager..."
    sleep 1
done

# Signal process started in appsupport-prepare that the hooks for prepare-post-hook.d
# can be run

if [ -e "$CONTROL_FILE_PATH" ]; then
    echo "ok" > "$CONTROL_FILE_PATH"
fi

while [ ! -f $ANDROID_DATA/alien_boot_completed ]; do sleep 1; done

systemd-notify --pid=$START_PID --ready
# Systemd has a bug and can't handle the situation that notifying daemon (this one)
# does exit before systemd has fully handled the notify message.
# Thus we need to stay here and make sure systemd has handled our notify message
# 60 attempts is a bit much and 5 should suffice, but let's be certain cause boot
# can be quite busy.
n=0
lxc_status=
while [ $n -lt 60 ]; do
    sleep 1
    if systemctl is-active --quiet $CONTAINER_SERVICE; then
        lxc_status=active
        break
    fi
    echo "info systemd again..."
    systemd-notify --pid=$START_PID --ready
    : $((n=n+1))
done

if [ "$lxc_status" = "active" ]; then
    exit 0
else
    echo "Couldn't deliver notify message to systemd"
    exit 1
fi

) &

lxc-start --rcfile=$CONTAINER_CONFIG_FILE --lxcpath=$LXC_CONFIG_PATH -n $INSTANCE_NAME -F

# zygote crash
if [ "$(cat $ANDROID_DATA/alien_boot_completed)" = "2" ]; then
    exit 1
fi

if [ "$(cat $ANDROID_DATA/alien_restart_requested)" = "yes" ]; then
    exit 2
fi

exit 0

