#!/system/bin/sh
# Runs the Rust vibrator HAL in place of the installed one until the next reboot.
# Run as root from this folder's copy on the phone. Nothing is written to /vendor.
[ -n "$VIB_NS" ] || exec nsenter -t 1 -m -- env VIB_NS=1 sh "$0" "$@"
D=$(cd "${0%/*}" && pwd)
SVC=vendor.qti.vibrator
NAME=vendor.qti.hardware.vibrator.service.oplus_sm8750
BIN=/vendor/bin/hw/$NAME
LIB=/vendor/lib64/libqtivibratoreffect.oplus.dodge.so
# /dev is nosuid, which blocks the init -> hal_vibrator_default transition; use our own tmpfs.
T=/mnt/penguin_vib
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 half swapped.
restore() {
    if [ "$(getprop init.svc.$SVC)" != running ]; then
        echo "FAILED: restoring the installed HAL"
        stop $SVC
        umount $BIN 2>/dev/null
        umount $LIB 2>/dev/null
        start $SVC
    fi
}
trap restore EXIT

cd "$D" || exit 1
grep -E "oplus_sm8750$|oplus.dodge.so$" SHA256SUMS | sha256sum -c - || exit 1
if grep -q " $BIN " /proc/mounts; then
    echo "Already swapped; run revert-vib-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_vib $T || exit 1
cp $NAME libqtivibratoreffect.oplus.dodge.so $T/ || exit 1
chmod 755 $T/$NAME
chmod 644 $T/libqtivibratoreffect.oplus.dodge.so
chcon "$(ls -Z $BIN | cut -d' ' -f1)" $T/$NAME || exit 1
chcon "$(ls -Z $LIB | cut -d' ' -f1)" $T/libqtivibratoreffect.oplus.dodge.so || exit 1

stop $SVC
mount --bind $T/libqtivibratoreffect.oplus.dodge.so $LIB &&
    mount --bind $T/$NAME $BIN &&
    start $SVC
sleep 3

{
    echo "service: $(getprop init.svc.$SVC)"
    stats after
    logcat -d -s vendor.qti.vibrator vendor.qti.vibratorCL | tail -8
} >> "$REPORT"
cat "$REPORT"
echo "Report saved to $REPORT. After testing, run: sh $D/check-vib-rust.sh"
