#!/bin/bash
# -----------------------------------------------------------------------------
# This script manages the U-Boot environment variable 'timing_selected'.
# U-Boot will use this variable to patch the device tree to use the corresponding timing node.
# It can:
# 1. Set the variable based on a provided display timing argument.
# 2. Clear the variable if the '-c' option is used.
# 3. Print available display timings with the '-s' option.
# The script checks for the existence of the timing in the device tree exposed in the procfs.
#
# Usage:       ./set-display-timing [-c | -s | <display_timing>]
#              Examples:
#              - ./set-display-timing "EVTEC-800"    # Set timing
#              - ./set-display-timing -c             # Clear timing
#              - ./set-display-timing -s             # Show available timings
# -----------------------------------------------------------------------------

# Path in the device tree containing the display timings
TIMINGS_DIR="/proc/device-tree/ldb/lvds-channel@1/display-timings"

# Store available timings, ignoring "name" and "native-mode"
AVAILABLE_TIMINGS=$(ls "$TIMINGS_DIR" | grep -vE "name|native-mode")

check_timing_exists() {
    local timing=$1

    if echo "$AVAILABLE_TIMINGS" | grep -q "^$timing$"; then
        return 0 # Timing exists
    else
        return 1 # Timing does not exist
    fi
}

print_available_timings() {
    echo "Available display timings:"
    echo "$AVAILABLE_TIMINGS"
}

get_current_uboot_timing() {
    fw_printenv timing_selected | cut -d'=' -f2
}

set_uboot_timing() {
    local timing=$1
    fw_setenv timing_selected "$timing"
}

clear_uboot_timing() {
    fw_setenv timing_selected
}

if [ $# -ne 1 ]; then
    echo "Usage: $0 [-c | -s | <display_timing>]"
    exit 1
fi


case $1 in
    -c)
        clear_uboot_timing
        echo "The 'timing_selected' variable has been cleared."
        exit 0
        ;;
    -s)
        print_available_timings
        exit 0
        ;;
    *)
        timing=$1
        ;;
esac

if ! check_timing_exists "$timing"; then
    echo "Error: Timing '$timing' not known."
    exit 1
fi

current_timing=$(get_current_uboot_timing)

if [ "$current_timing" == "$timing" ]; then
    echo "Timing '$timing' is already set. No change needed."
else
    set_uboot_timing "$timing"
    echo "Timing '$timing' has been set successfully."
fi
