#!/usr/bin/env bash
set -euo pipefail

MARKER_FILE="/etc/kiwy-signage/pi_boot_config_patched.marker"

is_pi() {
    if [[ -f /proc/device-tree/model ]] && grep -qi "raspberry pi" /proc/device-tree/model; then
        return 0
    fi

    if grep -qi "raspberry" /proc/cpuinfo 2>/dev/null; then
        return 0
    fi

    return 1
}

find_boot_config() {
    if [[ -f /boot/firmware/config.txt ]]; then
        echo "/boot/firmware/config.txt"
    elif [[ -f /boot/config.txt ]]; then
        echo "/boot/config.txt"
    else
        echo ""
    fi
}

upsert_key() {
    local key="$1"
    local value="$2"
    local file="$3"

    if grep -Eq "^[#[:space:]]*${key}=" "$file"; then
        sed -i -E "s|^[#[:space:]]*${key}=.*|${key}=${value}|" "$file"
    else
        echo "${key}=${value}" >> "$file"
    fi
}

if [[ "${EUID}" -ne 0 ]]; then
    echo "[pi-boot-patch] Please run as root."
    exit 1
fi

if ! is_pi; then
    echo "[pi-boot-patch] Not a Raspberry Pi. Skipping."
    exit 0
fi

if [[ -f "$MARKER_FILE" ]]; then
    echo "[pi-boot-patch] Patch already applied. Skipping."
    exit 0
fi

BOOT_CONFIG="$(find_boot_config)"
if [[ -z "$BOOT_CONFIG" ]]; then
    echo "[pi-boot-patch] Boot config not found. Skipping."
    exit 0
fi

echo "[pi-boot-patch] Applying patch to ${BOOT_CONFIG}"

# Graphics and memory settings for smoother Chromium playback on Pi.
upsert_key "dtoverlay" "vc4-kms-v3d" "$BOOT_CONFIG"
upsert_key "gpu_mem" "256" "$BOOT_CONFIG"
upsert_key "disable_overscan" "1" "$BOOT_CONFIG"

# Keep HDMI and display active for kiosk use.
upsert_key "hdmi_blanking" "0" "$BOOT_CONFIG"
upsert_key "hdmi_ignore_cec_init" "1" "$BOOT_CONFIG"
upsert_key "hdmi_force_hotplug" "1" "$BOOT_CONFIG"

mkdir -p "$(dirname "$MARKER_FILE")"
date -u +"%Y-%m-%dT%H:%M:%SZ" > "$MARKER_FILE"

echo "[pi-boot-patch] Patch complete. Marker written to ${MARKER_FILE}"
