#!/bin/sh

if [ ! -e /dev/ipa ]; then
    exit 0
fi
while ! mountpoint -q -- /android/vendor
do
    sleep 1
done
if [ -f /vendor/firmware/ipa_fws.mdt ]; then
    echo 1 > /dev/ipa
fi

# While the time_daemon binary has been overlayed by a non-executable, Android
# init will continue trying to restart that service. Stop the cycle by
# explicitly tell it to stop.
setprop ctl.stop time_daemon

# Set schedtune boost
# cgroup v1 (20.04)
if [ -e /sys/fs/cgroup/schedtune/schedtune.boost ]; then
    echo 20 > /sys/fs/cgroup/schedtune/schedtune.boost
    echo 1 > /sys/fs/cgroup/schedtune/schedtune.prefer_idle
# cgroup v2 (24.04)
elif [ -e /sys/fs/cgroup/user.slice/schedtune.boost ]; then
    echo 20 > /sys/fs/cgroup/user.slice/schedtune.boost
    echo 1 > /sys/fs/cgroup/user.slice/schedtune.prefer_idle
fi

# binfmt_misc support
if ! mountpoint -q /proc/sys/fs/binfmt_misc; then
    mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc
    systemctl restart systemd-binfmt.service
fi

# Silence Android init failing to find a QCOM service for cacert management
systemctl start dummy_cacert.service

# Post-boot recovery update. This is done because old versions of recovery is
# missing the entry for recovery partition in fstab, which means recovery
# couldn't be updated automatically.

# FIXME: this assumes we always boot from slot A.
recovery_part=/dev/disk/by-partlabel/recovery_a
recovery_base=/opt/recovery-update
recovery_file=${recovery_base}/recovery.img.xz
recovery_size_file=${recovery_base}/recovery.img_size
recovery_hash_file=${recovery_base}/recovery.img_sha256sum

if  [ -e ${recovery_file} ] && \
    [ -e ${recovery_size_file} ] && \
    [ -e ${recovery_hash_file} ] \
; then
    recovery_size=$(cat "$recovery_size_file")
    recovery_hash=$(cat "$recovery_hash_file")
    recovery_part_size=$(blockdev --getsize64 "$recovery_part")

    # Sanity check: image size must be less than or equal to partition size.
    if [ "$recovery_size" -gt "$recovery_part_size" ]; then
        echo "WARNING: recovery image is larger than partition." \
             "Can't update recovery." >&2
        exit 1
    fi

    recovery_part_hash=$(
        head -c "$recovery_size" "$recovery_part" | sha256sum | cut -d' ' -f1)

    if [ "$recovery_hash" = "$recovery_part_hash" ]; then
        echo "Recovery partition is up-to-date." >&2
    else
        xzcat "$recovery_file" >"$recovery_part"
        echo "Recovery partition is updated to hash ${recovery_hash}." >&2
    fi
fi
