#!/usr/bin/env bash
# Extract libcamera enumeration output as C++ BakedCameraProfile initializer rows.
#
# Usage:
#   scripts/extractBakedCameraProfiles.sh <build-dir> <machine-tag>
#
# Example:
#   scripts/extractBakedCameraProfiles.sh build-agent dell-laptop

set -euo pipefail

if [[ $# -lt 2 ]]; then
	echo "Usage: $0 <build-dir> <machine-tag>" >&2
	exit 1
fi

BUILD_DIR="$1"
MACHINE_TAG="$2"
LIST_CAMERAS="${BUILD_DIR}/commonLibs/lcameraDev/lcameraDev_list_cameras"

if [[ ! -x "${LIST_CAMERAS}" ]]; then
	echo "Missing executable: ${LIST_CAMERAS}" >&2
	echo "Build with -DENABLE_LIB_lcameraDev=ON -DENABLE_TESTS=ON" >&2
	exit 1
fi

echo "// MACHINE: ${MACHINE_TAG}"
echo "// Paste rows into tests/fixtures/bakedCameraProfiles.h"
echo

"${LIST_CAMERAS}" 2>/dev/null | awk -v machine="${MACHINE_TAG}" '
/^lcameraDev: found / { next }
/^\s+\[[0-9]+\] id=/ {
	line = $0
	sub(/^\s+\[[0-9]+\] /, "", line)

	id = ""
	model = ""
	location = ""

	n = split(line, parts, " ")
	for (i = 1; i <= n; i++) {
		if (parts[i] ~ /^id=/) {
			id = substr(parts[i], 4)
		} else if (parts[i] ~ /^model=/) {
			model = substr(parts[i], 7)
		} else if (parts[i] ~ /^location=/) {
			location = substr(parts[i], 10)
		}
	}

	profile_tag = "camera_index_" index
	if (location == "external") {
		profile_tag = "usb_camera"
	} else if (location == "front" || location == "back") {
		profile_tag = "integrated_webcam"
	}

	selector = "index:" index
	if (model != "") {
		selector = "model-substr:" substr(model, 1, 12)
		if (location != "") {
			selector = selector ";location:" location
		}
	}

	printf "{\n"
	printf "\t\"%s\",\n", machine
	printf "\t\"%s\",\n", profile_tag
	printf "\t\"%s\",\n", id
	printf "\t\"%s\",\n", model
	printf "\t\"%s\",\n", location
	printf "\t\"\",\n"
	printf "\t\"\",\n"
	printf "\t\"%s\",\n", selector
	printf "\ttrue,\n"
	printf "},\n"
}
' index=0
