#!/bin/bash
{
	#////////////////////////////////////
	# DietPi AutoStart Script
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - filename /DietPi/dietpi/dietpi-autostart
	#
	# Usage:
	# - dietpi-autostart   (menu system)
	# - dietpi-autostart int (set value only)
	#////////////////////////////////////

	#Grab Input (valid interger)
	INPUT=-1
	if [[ $1 =~ ^-?[0-9]+$ ]]; then

		INPUT=$1

	fi

	#Import DietPi-Globals ---------------------------------------------------------------
	. /DietPi/dietpi/func/dietpi-globals
	G_CHECK_ROOT_USER
	export G_PROGRAM_NAME='DietPi-Autostart'
	#Import DietPi-Globals ---------------------------------------------------------------

	#/////////////////////////////////////////////////////////////////////////////////////
	# MENUS
	#/////////////////////////////////////////////////////////////////////////////////////
	WHIP_BACKTITLE='DietPi-AutoStart'
	WHIP_TITLE=$WHIP_BACKTITLE
	CHOICE=0
	OPTION=0
	TARGETMENUID=0

	AUTO_START_INDEX=0

	Apply_Boot_Index(){

		#Always disable LightDM
		systemctl disable lightdm.service &> /dev/null

		# - Amiberry | always disable services, service launched by DietPi/boot if non fastboot mode
		systemctl disable amiberry.service &> /dev/null
		systemctl disable amiberry-sdl2.service &> /dev/null

		sed -i '/^boot_delay=0/d' /DietPi/config.txt

		if [ -f /boot/cmdline.txt ]; then

			sed -i 's/logo.nologo//' /boot/cmdline.txt
			sed -i 's/loglevel=3//' /boot/cmdline.txt
			sed -i 's/console=tty3/console=tty1/' /boot/cmdline.txt

		fi

		# - Disable custom launch service
		rm /etc/systemd/system/dietpi-autostart_custom.service &> /dev/null

		# - Disable auto login
		rm /etc/systemd/system/getty@tty1.service.d/autologin.conf &> /dev/null

		#----------------------------------------------------------------------
		#Enable autoboot options
		#	Custom script, service without auto login: https://github.com/Fourdee/DietPi/issues/1024
		if (( $AUTO_START_INDEX == 14 )); then

			cat << _EOF_ > /etc/systemd/system/dietpi-autostart_custom.service
[Unit]
Description=DietPi autostart (Custom /var/lib/dietpi/dietpi-autostart/custom.sh)
After=dietpi-boot.service dietpi-ramdisk.service dietpi-ramlog.service rc-local.service
Requires=dietpi-boot.service dietpi-ramdisk.service

[Service]
Type=idle
ExecStartPre=/bin/bash echo -e 'Starting DietPi-Autostart (Custom) script'
ExecStart=/bin/bash -c /var/lib/dietpi/dietpi-autostart/custom.sh
StandardOutput=tty
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
_EOF_
		systemctl enable dietpi-autostart_custom.service

		#	Uae4arm special | fast boot via enabled service
		elif (( $AUTO_START_INDEX == 6 || $AUTO_START_INDEX == 12 )); then

			#SDL1
			if (( $AUTO_START_INDEX == 6 )); then

				systemctl enable amiberry.service

			#SDL2
			else

				systemctl enable amiberry-sdl2.service

			fi

			# - apply tweaks
			if (( ! $(cat /DietPi/config.txt | grep -ci -m1 '^boot_delay=0') )); then

				echo -e "boot_delay=0\n" >> /DietPi/config.txt

			fi

			if (( ! $(cat /boot/cmdline.txt | grep -ci -m1 ' logo.nologo') )); then

				sed -i 's/rootwait/rootwait logo.nologo/' /boot/cmdline.txt

			fi

			if (( ! $(cat /boot/cmdline.txt | grep -ci -m1 ' loglevel=3') )); then

				sed -i 's/rootwait/rootwait loglevel=3/' /boot/cmdline.txt

			fi

			if (( ! $(cat /boot/cmdline.txt | grep -ci -m1 ' console=tty3') )); then

				sed -i 's/console=tty1/console=tty3/' /boot/cmdline.txt

			fi

		#	Enable auto login
		elif (( $AUTO_START_INDEX > 0 )); then

			mkdir -p /etc/systemd/system/getty@tty1.service.d &> /dev/null
			cat << _EOF_ > /etc/systemd/system/getty@tty1.service.d/autologin.conf
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin root %I $TERM
_EOF_

		fi

		#Amiberry (RPi) lower framebuffer size to increase memory performance: https://github.com/Fourdee/DietPi/issues/474#issuecomment-243124631
		if (( $G_HW_MODEL < 10 )); then

			if (( $AUTO_START_INDEX == 6 || $AUTO_START_INDEX == 8 || $AUTO_START_INDEX == 12 || $AUTO_START_INDEX == 13 )); then

				sed -i '/framebuffer_width=/c\framebuffer_width=854' /DietPi/config.txt
				sed -i '/framebuffer_height=/c\framebuffer_height=480' /DietPi/config.txt

			fi

		fi

		#Save boot index.
		echo -e "$AUTO_START_INDEX" > /DietPi/dietpi/.dietpi-autostart_index

		systemctl daemon-reload

	}

	#TARGETMENUID=0
	Menu_Main(){

		#existing boot flag
		AUTO_START_INDEX=$(cat /DietPi/dietpi/.dietpi-autostart_index)

		local option_name=(
			'0' 'Console:           Manual login (default)'
			'7' 'Console:           Automatic login'
			'6' 'AmiBerry SDL1:     Fast boot'
			'8' 'AmiBerry SDL1:     Standard boot'
			'12' 'AmiBerry SDL2:     Fast boot'
			'13' 'AmiBerry SDL2:     Standard boot'
			'10' 'CAVA Spectrum'
			'11' 'Chromium:          Without desktop'
			'14' 'Custom:            /var/lib/dietpi/dietpi-autostart/custom.sh'
			'2' 'Desktops:          Automatic login (recommended)'
			'16' 'Desktops:          LightDM login prompt'
			'5' 'DietPi-Cloudshell'
			'9' 'DXX-Rebith:        Descent 1/2'
			'15' 'JRiver'
			'1' 'Kodi'
			'4' 'OpenTyrian'
			'3' 'RetroPie'
		)

		OPTION=$(whiptail --title "$WHIP_TITLE" --menu "Current AutoStart Option: $AUTO_START_INDEX\n\nNB: If your choice is not \"Console:\", please ensure required software is installed (or selected for install) in DietPi-Software." --cancel-button "Back" --backtitle "$WHIP_BACKTITLE" --default-item "$AUTO_START_INDEX" 20 75 9 "${option_name[@]}" 3>&1 1>&2 2>&3)
		CHOICE=$?

		if (( $CHOICE == 0 )); then

			#Apply Selected boot option
			AUTO_START_INDEX=$OPTION

			Apply_Boot_Index

			#AmiBerry fast boot info
			if (( $OPTION == 6 )); then

				whiptail --title "AmiBerry: (Fast boot)" --msgbox "AmiBerry: (Fast boot):\nA highly optimized and tweaked boot mode.\nThis mode allows for a < 2.5 second boot on a RPi 3, into AmiBerry.\n\nIf you experience boot issues with this mode, please try (Standard Boot)" --backtitle "$WHIP_BACKTITLE" 14 70

			fi

			#Custom info
			if (( $OPTION == 14 )); then

				#	create template
				if [ ! -f /var/lib/dietpi/dietpi-autostart/custom.sh ]; then

					mkdir -p /var/lib/dietpi/dietpi-autostart
					cat << _EOF_ > /var/lib/dietpi/dietpi-autostart/custom.sh
#!/bin/bash
#---Examples---

# - Chromium
#xinit chromium

# - LXDE
#startx

# - Print hello
#echo -e "Hello"

#---Put your code below this line---

_EOF_

				chmod +x /var/lib/dietpi/dietpi-autostart/custom.sh

				#	Service

				whiptail --title "Custom: /var/lib/dietpi/dietpi-autostart/custom.sh" --msgbox "A template script has been created:\n - /var/lib/dietpi/dietpi-autostart/custom.sh\n\nPlease edit this file and enter the required commands you wish to launch. DietPi will then execute this script during boot." --backtitle "$WHIP_BACKTITLE" 14 70

				fi

			fi

		else

			#Exit
			TARGETMENUID=-1

		fi

		unset option_name

	}

	#/////////////////////////////////////////////////////////////////////////////////////
	# Main Loop
	#/////////////////////////////////////////////////////////////////////////////////////
	#Start Menu
	if (( $INPUT == -1 )); then

		while (( $TARGETMENUID > -1 )); do

			#Clear Screen buffer
			clear

			if (( $TARGETMENUID == 0 )); then
				Menu_Main
			fi
		done

	#Apply boot index
	elif (( $INPUT >= 0 )); then

		AUTO_START_INDEX=$INPUT
		Apply_Boot_Index

	fi

	#-----------------------------------------------------------------------------------
	exit
	#-----------------------------------------------------------------------------------
}