#!/system/bin/sh
# CamSwapper HAL Hook - Root module post-fs-data script
# Runs BEFORE class_start hal.
# Strategy: Use wrap. property to inject LD_PRELOAD into cameraserver.
# On Pixel devices, the camera HAL is loaded in-process by cameraserver,
# not as a separate provider service.

MODDIR="${0%/*}"
HOOK_LIB="$MODDIR/libcamera_hook.so"
CONFIG_DIR="/data/local/camera_magic"

mkdir -p "$CONFIG_DIR"
chmod 755 "$CONFIG_DIR"

if [ ! -f "$CONFIG_DIR/config.txt" ]; then
    echo "enabled=0" > "$CONFIG_DIR/config.txt"
    echo "source_mode=file" >> "$CONFIG_DIR/config.txt"
    echo "video_path=/data/local/camera_magic/video.mp4" >> "$CONFIG_DIR/config.txt"
    echo "rtsp_url=" >> "$CONFIG_DIR/config.txt"
    chmod 644 "$CONFIG_DIR/config.txt"
fi

if [ ! -f "$HOOK_LIB" ]; then
    echo "CameraHook: ERROR - libcamera_hook.so not found" > /dev/kmsg
    exit 1
fi

chmod 644 "$HOOK_LIB"

cp "$HOOK_LIB" "$CONFIG_DIR/libcamera_hook.so"
chmod 644 "$CONFIG_DIR/libcamera_hook.so"

# Apply SELinux policy rules
if command -v magiskpolicy >/dev/null 2>&1; then
    magiskpolicy --live \
        "allow hal_camera_default magisk_file file { read open execute execute_no_trans map }" \
        "allow hal_camera_default system_data_file dir { search open read }" \
        "allow hal_camera_default system_data_file file { read open getattr }" \
        "allow hal_camera_default self memfd { create read write map }" \
        "allow hal_camera_default ashmem_device chr_file { read write open ioctl map }" \
        "allow hal_camera_default logd unix_dgram_socket { sendto write }" \
        "allow hal_camera_default logdw sock_file { write }" \
        "allow cameraserver magisk_file file { read open execute execute_no_trans map }" \
        "allow cameraserver magisk_file dir { search open read }" \
        "allow cameraserver system_data_file dir { search open read }" \
        "allow cameraserver system_data_file file { read open getattr map }" 2>/dev/null
    echo "CameraHook: SELinux policy applied" > /dev/kmsg
else
    echo "CameraHook: magiskpolicy not found, relying on sepolicy.rule" > /dev/kmsg
fi

echo "CameraHook: post-fs-data complete, hook lib ready at $CONFIG_DIR/libcamera_hook.so" > /dev/kmsg
