#!/bin/bash

if [ ! "$(id -u)" = "0" ] ; then
  echo "$0 requires root to run. Exiting."
  exit
fi

clear
# Set default resolution
X=80
Y=20
if which resize > /dev/null; then
	eval $(resize)
	X=$COLUMNS
	Y=$LINES
fi

# Detect family
for comp in $(cat "/proc/device-tree/compatible" | tr '\0' '\n'); do
	if [[ "$comp" == "allwinner,sun"* ]]; then
		soc=$(cut -d',' -f2 <<< $comp)
	elif [[ "$comp" == "st,stm32mp1"* ]]; then
                soc="stm32mp1"
	elif [[ "$comp" == "olimex,"* ]]; then
		board="${comp}"
	fi
done

if [[ -z ${soc} ]]; then
	echo "The board is not Allwinner SoC. Exiting."
	exit 0
fi

if [[ ! -d "/usr/lib/olinuxino-overlays/${soc}" ]]; then
	echo "The ${soc} SoC family is not supported. Exiting."
	exit 0
fi

function display_reboot_dialog()
{
	whiptail --title "Almost done" --backtitle "${BACKTITLE}" --yes-button "Reboot" --no-button "Exit" --yesno "All done. \n
Board must be rebooted to apply changes." 7 70
	[[ $? -ne 0 ]] && exit 0
	sync
	reboot
}

# Get currently installed overlays
INSTALLED=""
if [[ -e "/boot/uEnv.txt" ]]; then
	while read line; do
		if [[ "$line" == "fdtoverlays="* ]]; then
			INSTALLED="$(cut -d '=' -f2 <<< "$line")"
			break
		fi
	done <<< "$(cat "/boot/uEnv.txt")"
fi

# Source available files
OVERLAYS=()
MENU=()
for f in $(find "/usr/lib/olinuxino-overlays/${soc}/" -type f -name "*.dtbo" | sort); do

	# Check if overlay is compatible
	compatible="$(fdtget $f / compatible)"

	grep -q -w "allwinner,${soc}" <<< ${compatible} || \
	grep -q -w "${board}" <<< ${compatible} || continue

	OVERLAYS+=("$f")
	MENU+=("$(basename $f)" "$(fdtget $f / description)")

	if [[ "$INSTALLED" == *"$(basename $f)"* ]]; then
		MENU+=("ON")
	else
		MENU+=("OFF")
	fi
done

RESULT=$(mktemp)
whiptail --title "Enable FDT overlays" --checklist --separate-output \
"Available overlays:" $Y $X $(( $Y - 8 )) "${MENU[@]}" 2>${RESULT}

# meh. do not touch uEnv.txt on cancel..
exitstatus=$?
if [ "$exitstatus" != "0" ]; then
  exit 0
fi

# Get enabled overlays
ENABLED=()
while read line; do
	ENABLED+=("$line")
done < ${RESULT}
rm -f ${RESULT}

# Finally enable/disable overlays
LIST="fdtoverlays="

# Get custom overlays
for overlay in ${INSTALLED[@]}; do
	# Check if overlay is custom overlay
	if [[ ! "${OVERLAYS[@]}" =~ "$overlay" ]]; then
		LIST="$LIST$overlay "
	fi
done

# Add olimex provided overlays
for overlay in ${OVERLAYS[@]}; do
	if [[ "${ENABLED[@]}" =~ "$(basename $overlay)" ]]; then
		LIST="$LIST$overlay "
	fi
done

# Modify /boot/uEnv.txt
if [[ ! -e "/boot/uEnv.txt" ]] || ! grep -q "^fdtoverlays=" "/boot/uEnv.txt"; then
	echo $LIST >> "/boot/uEnv.txt"
else
	sed -i "s/fdtoverlays=.*/${LIST//\//\\/}/g" "/boot/uEnv.txt"
fi

display_reboot_dialog
