#!/bin/bash -e
#
# System-Info
# Copyright (C) 2013-2025 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com

theme="NorNet Management"
image="/usr/share/nornet-desktop/Desktop-with-Logo/TimeSrv1"   #  "/boot/NorNet/Management1"


# ====== Make a table of all images and their dimensions ====================
imageDirectory=$(dirname ${image})
imagePrefix=$(basename ${image})


imageTable=$(find "${imageDirectory}" -name "${imagePrefix}*" | (
   while read -r imageName ; do
      # shellcheck disable=SC2001
      imageWidth=$(echo "${imageName}" | sed -e "s/^.*\/${imagePrefix}-\([0-9]*\)x\([0-9]*\).*$/\1/g")
      imageHeight=$(echo "${imageName}" | sed -e "s/^.*\/${imagePrefix}-\([0-9]*\)x\([0-9]*\).*$/\2/g")
      imageSize=$((imageWidth*imageHeight))
      imageAspectRatio=$((1000*imageWidth/imageHeight))
      echo "${imageName} ${imageAspectRatio} ${imageSize} ${imageWidth} ${imageHeight}"
   done
) | sort -k 3nr)

# echo "${imageTable}"


background=""
screenResolutions=$(grep "^GRUB_GFXMODE=" /etc/default/grub | sed -e "s/GRUB_GFXMODE=//g" -e "s/[,\"]/ /g")
for screenResolution in ${screenResolutions} 1024x768 ; do
   if [[ "${screenResolution}" =~ ^[0-9]*x[0-9]* ]] ; then
      # shellcheck disable=SC2001
      screenWidth=$(echo "${screenResolution}" | sed -e "s/\([0-9]*\)x\([0-9]*\).*/\1/g")
      # shellcheck disable=SC2001
      screenHeight=$(echo "${screenResolution}" | sed -e "s/\([0-9]*\)x\([0-9]*\).*/\2/g")
      screenAspectRatio=$((1000*screenWidth/screenHeight))

      imageToUse=$(echo "${imageTable}" | while read -r imageName imageAspectRatio imageSize imageWidth imageHeight ; do
         if [ "${imageAspectRatio}" = "${screenAspectRatio}" ] ; then
            echo "${imageName}"
            break
         fi
      done)

      if [ -e "${imageToUse}" ] ; then
         background="${imageToUse}"
         break
      fi
   fi
done

echo >&2 "Using ${theme} theme from ${background}"
