#!/bin/bash

# This file is a part of TorBox, an easy to use anonymizing router based on Raspberry Pi.
# This file is a modified version of the file on https://github.com/goodtft/LCD-show
# Latest commit of the original file: 957fa6c on 29 July 2022
#
# DESCRIPTION
# This file installs the support for no-name 3.5″ TFTs.
#
# SYNTAX
# ./LCD35-show <rotation>
#
# Optional, the <rotation> can be changed to 0, 90, 180 and 270, respectively representing
# rotation angles of 0 degrees, 90 degrees, 180 degrees, 270 degrees.
#
###### SET VARIABLES ######
# How many degrees should the display output be rotated?
ROTATE=$(($1))

# What main version is installed
DEBIAN_VERSION=$(sed 's/\..*//' /etc/debian_version)

# Where is the config.txt?
if [ "$DEBIAN_VERSION" -gt "11" ]; then
  CONFIGFILE="/boot/firmware/config.txt"
else
  CONFIGFILE="/boot/config.txt"
fi

# Where is the cmdline.txt?
if [ "$DEBIAN_VERSION" -gt "11" ]; then
  CMDLINEFILE="/boot/firmware/cmdline.txt"
else
  CMDLINEFILE="/boot/cmdline.txt"
fi

sudo cp ./usr/tft35a-overlay.dtb /boot/overlays/
sudo cp ./usr/tft35a-overlay.dtb /boot/overlays/tft35a.dtbo

# By TorBox
if ! grep "# Added by LCD-show" ${CONFIGFILE} ; then
  sudo printf "\n# Added by LCD-show\nhdmi_force_hotplug=1\ndtparam=i2c_arm=on\ndtparam=spi=on\nenable_uart=1\ndtoverlay=tft35a:rotate=$ROTATE\nhdmi_group=2\nhdmi_mode=1\nhdmi_mode=87\nhdmi_cvt 480 320 60 6 0 0 0\nhdmi_drive=2\n" | sudo tee -a ${CONFIGFILE}
else
	sudo sed -i "s/^dtoverlay=tft35a:rotate=.*/dtoverlay=tft35a:rotate=$ROTATE/g" ${CONFIGFILE}
fi

if ! grep "fbcon=map:10" /boot/cmdline.txt ; then
  CMDLINE=$(<${CMDLINEFILE})
  CMDLINE=${CMDLINE//[$'\n']}
  CMDLINE="$CMDLINE fbcon=map:10"
  echo "$CMDLINE" > ${CMDLINEFILE}
fi
