#!/bin/bash
# SPDX-License-Identifier: MIT
# Copyright (C) 2023 JELOS (https://github.com/JustEnoughLinuxOS)
# Copyright (C) 2023-present christianhaitian (https://github.com/christianhaitian)
# Copyright (C) 2023-present Rocky5 (https://github.com/rocky5)

# The purpose of this script is to permanently set the resolution
# output for hdmi when connected.

xres="$(cat /sys/class/graphics/fb0/modes | grep -o -P '(?<=:).*(?=p-)' | cut -dx -f1)"

# drm_tool source available at https://github.com/christianhaitian/drm_tool.git

mode="$(/usr/bin/drm_tool list |  awk '/1280x720.*60/ {print substr($2,1,length($2)-1); exit}')"
mode2="$(/usr/bin/drm_tool list |  awk '/1920x1080.*60/ {print substr($2,1,length($2)-1); exit}')"

# Now we tell drm what the hdmi mode is by writing to /var/run/drmMode
# This will get picked up by SDL2 as long as it's been patched with the batocera
# drm resolution patch.  This patch can be found at 
# https://github.com/christianhaitian/rk3566_core_builds/raw/master/patches/sdl2-patch-0003-drm-resolution.patch

if [ $xres -eq "1280" ]; then
  echo $mode | tee /var/run/drmMode
elif [ $xres -eq "1920" ]; then
  echo $mode2 | tee /var/run/drmConn
else
  echo 0 | tee /var/run/drmMode
  echo 1 | tee /var/run/drmConn
fi
