#!/system/bin/sh
MODDIR="${0%/*}"
HOOK_LIB="$MODDIR/libcamera_hook.so"
MODPROP="$MODDIR/module.prop"
INJECTOR="/data/local/tmp/inject_dlopen"

update_description() {
    if [ -f "$MODPROP" ]; then
        sed -i "s|^description=.*|description=$1|" "$MODPROP"
    fi
}

update_description "Waiting for cameraserver..."

if [ ! -f "$HOOK_LIB" ]; then
    update_description "Error - libcamera_hook.so not found"
    exit 1
fi

for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
    CS_PID=$(pidof cameraserver 2>/dev/null)
    if [ -n "$CS_PID" ]; then
        break
    fi
    sleep 1
done

if [ -z "$CS_PID" ]; then
    update_description "Error - cameraserver not running"
    exit 1
fi

sleep 2

if [ -f "$INJECTOR" ]; then
    "$INJECTOR" "$CS_PID" > /dev/kmsg 2>&1
    sleep 1
fi

if grep -q "libcamera_hook.so" /proc/"$CS_PID"/maps 2>/dev/null; then
    update_description "Active - hook loaded in cameraserver PID $CS_PID"
else
    update_description "cameraserver PID $CS_PID - injection attempted"
fi
