#!/system/bin/sh
# Runs the Rust power HAL in place of the installed one until the next reboot, then restarts the
# framework so every app and SurfaceFlinger opens fresh hint sessions with it. The screen goes
# black for a few seconds. Run as root from this folder's copy on the phone. Nothing is written
# to /vendor.
[ -n "$PWR_NS" ] || exec nsenter -t 1 -m -- env PWR_NS=1 sh "$0" "$@"
D=$(cd "${0%/*}" && pwd)
SVC=vendor.power
NAME=android.hardware.power-service
BIN=/vendor/bin/hw/$NAME
# /dev is nosuid, which blocks the init -> hal_power_default transition; use our own tmpfs.
T=/mnt/penguin_power
REPORT=$D/report-$(date +%H%M%S).txt

stats() {
    pid=$(pidof $NAME)
    echo "$1: pid $pid threads $(ls /proc/$pid/task 2>/dev/null | wc -l)" \
        "$(grep -E '^(Pss|Rss):' /proc/$pid/smaps_rollup 2>/dev/null | tr -s ' ' | tr '\n' ' ')"
}

# Whatever happens below, never leave the service stopped or swapped to a broken binary.
restore() {
    if [ "$(getprop init.svc.$SVC)" != running ]; then
        echo "FAILED: restoring the installed HAL"
        stop $SVC
        umount $BIN 2>/dev/null
        start $SVC
    fi
}
trap restore EXIT

cd "$D" || exit 1
grep -E " $NAME$" SHA256SUMS | sha256sum -c - || exit 1
if grep -q " $BIN " /proc/mounts; then
    echo "Already swapped; run revert-power-rust.sh first"
    exit 1
fi

{
    stats before
    echo "crash buffer before:"
    logcat -b crash -d | tail -3
} > "$REPORT"

mkdir -p $T
grep -q " $T tmpfs " /proc/mounts || mount -t tmpfs -o mode=0755 penguin_power $T || exit 1
cp $NAME $T/ || exit 1
chmod 755 $T/$NAME
chcon "$(ls -Z $BIN | cut -d' ' -f1)" $T/$NAME || exit 1

stop $SVC
mount --bind $T/$NAME $BIN && start $SVC
sleep 3

{
    echo "service: $(getprop init.svc.$SVC)"
    stats after
    logcat -d -s "QTI PowerHAL" | tail -8
} >> "$REPORT"
cat "$REPORT"

if [ "$(getprop init.svc.$SVC)" = running ]; then
    echo "Restarting the framework in 2 s. Then run check-power-rust.sh."
    nohup sh -c 'sleep 2; stop; start' > /dev/null 2>&1 &
fi
