#!/bin/bash

get_parent_pid() {
    local depth=$1
    local pid=$2

    if (( depth <= 0 )); then
        echo "$pid"
        return
    fi

    ppid=$(awk '/^PPid:/ {print $2}' "/proc/${pid}/status")

    get_parent_pid $(($depth - 1)) "$ppid"
}

get_cmdline() {
    local pid=$1
    read -ra cmdline < "/proc/${pid}/cmdline"
    echo "${cmdline[*]}"
}

if [ -d /astra_update ]; then
    parent_pid=$(get_parent_pid 3 $$)
    parent_cmdline=$(get_cmdline "$parent_pid")

    if [[ "$parent_cmdline" == *"astra-update-p"* ]]; then
        echo "astra-update with -p flag, disable script /usr/sbin/astra-mobile-postinst"
        exit 0
    fi
fi

ENV_NONINTERACTIVE="DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true"
APT_OPTIONS="-o Acquire::Check-Valid-Until=false -o Acquire::Check-Date=false -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold"

env $ENV_NONINTERACTIVE apt-get $APT_OPTIONS install -y --reinstall astra-plasma-mobile-configs
genfly-dmconf

if [[ $(astra-modeswitch get) != "2" ]]; then
    sed -i "s/UserList=.*/UserList=true/" "$CHROOT_DIR"/etc/X11/fly-dm/fly-dmrc
    sed -i "s/PreselectUser=.*/PreselectUser=Previous/" "$CHROOT_DIR"/etc/X11/fly-dm/fly-dmrc
fi

systemctl enable getty@

/usr/sbin/astra-mobile-rootfs-update
/usr/sbin/set_wait_timeout.sh
/usr/sbin/astra-mobile-hardware-tuning-host

sudis_check=$(dpkg -l | grep -i "fly_dmgreet_sudis")
if [ ! -z "$sudis_check" ]; then
    if [ ! -z /var/lib/dpkg/info/fly_dmgreet_sudis.postinst ]; then
        /var/lib/dpkg/info/fly_dmgreet_sudis.postinst
    fi
fi

MACHINE_TYPE=""
if [ -e /etc/astra/machine_type ]; then
    MACHINE_TYPE=`cat /etc/astra/machine_type | head -1 | tr -s ' '`
    echo "astra-mobile: detected machine type $MACHINE_TYPE"
fi

if [[ "$MACHINE_TYPE" == *"KVADRAT.arm64.v1.rev1"* || "$MACHINE_TYPE" == *"ZHISD.arm64.v1.rev1"* ]]; then
    env $ENV_NONINTERACTIVE apt-get $APT_OPTIONS install -qq -y librockchip-mpp1 librockchip-vpu0 libv4l-rkmpp libfly-camera-plugin-kvadrat
fi
