#!/bin/bash
# Drop the relay's 180-degree rotation on boards whose sensor is mounted upright.
#
# The packaged pipeline rotates because the sensor is mounted inverted on the
# Panther Lake boards this package was first written for. On Lunar Lake it is
# not: the sensor reports camera_sensor_rotation = 0 and camera_orientation =
# Front, so the rotation turns an already-correct frame upside down. Keyed on
# the bridge ACPI id; anything not positively identified as Lunar Lake keeps
# the configured pipeline untouched:
#
#   INTC10DE  Lunar Lake     no rotation
#   INTC10E1  Panther Lake   rotate-180, as packaged
#   INTC10CF  Meteor Lake    rotate-180, as packaged
#   INTC10E0  Arrow Lake     rotate-180, as packaged
#
# Runs as v4l2-relayd@ipu7's ExecStartPre, after one that removes the previous
# override, so VIDEOSRC arrives parsed by systemd from the configured files.
# ExecStart re-reads the drop-in's optional EnvironmentFile, so an edited
# /etc/v4l2-relayd.d/ipu7.conf takes effect on the next start.

set -eu

out=/run/v4l2-relayd-ipu7-videosrc.env
rm -f "${out}"

shopt -s nullglob
lunar_lake=(/sys/bus/acpi/devices/INTC10DE:*)
shopt -u nullglob
((${#lunar_lake[@]} > 0)) || exit 0

src=${VIDEOSRC:-}
[[ -n ${src} ]] || exit 0
src=${src/ ! videoflip method=rotate-180/}
# Quote for systemd's EnvironmentFile parser, which unescapes these in "...".
src=${src//\\/\\\\}
src=${src//\"/\\\"}
src=${src//\$/\\\$}
src=${src//\`/\\\`}
printf 'VIDEOSRC="%s"\n' "${src}" >"${out}"
