#!/bin/sh

set -e

active_wayland_user=

for session in $(loginctl list-sessions --no-legend | awk '{ print $1 }'); do
    if [ "$(loginctl show-session --value -p Type ${session})" != "wayland" ]; then
        continue
    fi

    if [ "$(loginctl show-session --value -p Class ${session})" != "user" ]; then
        continue
    fi

    if [ "$(loginctl show-session --value -p Remote ${session})" != "no" ]; then
        continue
    fi

    if [ "$(loginctl show-session --value -p State ${session})" != "active" ]; then
        continue
    fi

    active_wayland_user="$(loginctl show-session --value -p Name ${session})"
    break
done

if [ "${active_wayland_user}" == "" ]; then
    echo "No active wayland session found"
    exit 1
fi

data_dir="/home/${active_wayland_user}/.local/share/appsupport/data/"

rm -f ${data_dir}/alien_boot_completed

(
    while [ ! -f ${data_dir}/alien_boot_completed ]; do
        sleep 1;
    done

    if [ "$(cat ${data_dir}/alien_boot_completed)" = "1" ]; then
        echo "alien bootup finished, running post startup"

# use the commands from alien-post-startup.sh script here
lxc-attach --name=aliendalvik --lxcpath=/tmp/appsupport -- /system/bin/sh -c ""

lxc-attach --name=aliendalvik --lxcpath=/tmp/appsupport -- /system/bin/sh -c "source /etc/mkshrc;
# enable gesture navigation
cmd overlay disable com.android.internal.systemui.navbar.gestural
cmd overlay enable com.android.internal.systemui.navbar.gestural"

        systemd-notify --ready
    fi
) &

lxc-start --rcfile=/tmp/appsupport/aliendalvik/config --lxcpath=/tmp/appsupport -n aliendalvik -F

if [ "$(cat ${data_dir}/alien_boot_completed)" = "2" ]; then
    echo "alien crashed"
    exit 1
fi

echo "alien graceful shutdown"
exit 0