#!/bin/bash
#
#Copyright 2012 - 2019 CurlyMo & mk01 <development@xbian.org>
#
#This file is part of XBian - XBMC on the Raspberry Pi.
#
#XBian 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.
#
#XBian 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 XBian. If not, see <http://www.gnu.org/licenses/>
#
set -o history
# This will only allow xbian-config to be run as root
if [ ! $(id -u) -eq 0 ]; then
	echo "This program must be run as root.";
	exit 0;
fi

rmtmp() {
    rm -f /run/xbian-config.$$
}

# Disable [ctrl]-c and [ctrl]-z actions
trap '' INT TSTP
#trap "{ test -e /run/xbian-config.umount && mountpoint -q /boot && umount /boot; rm -fr /run/xbian-config.$$ /run/xbian-config.umount; [ $GUIMODE -eq 1 ] && showMainCloseDlg; }" EXIT INT ERR
trap "{ rmtmp; env | grep -qw GUIMODE=1 && showMainCloseDlg; eval $(echo "sed -i '/$$/d' /run/lock/xbian-config"); }" EXIT ERR

#|------------------------------------|
#|          Global variables          |
#|------------------------------------|

# Title at the top of the dialog windows
BACKTITLE="XBian $(cat /etc/xbian_version)";

# Check if a reboot is needed
ASKFORREBOOT=0;

# Check if the package database needs to be updates
LOCALPKGDBUPDATED=0;
REMOTEPKGDBUPDATED=0;
APTUPDATELISTUPDATED=0;

# Standard delimiter
ORIGINALIFS=$IFS;

# Url for the main APT repository Package location
APTBASE="http://apt.xbian.org/"

# Location of the xbian-config script files
BASEPATH="/usr/local/include/xbian-config"

#Set GUI language
LANGUAGE="en"

#Check if xbian-config is run in GUI mode
export GUIMODE=1;

#|------------------------------------|
#|           Main program             |
#|------------------------------------|	
function showMainCloseDlg() {

	DOREBOOT=0;
	# Is a reboot needed for the changes to get effect
	if [ $ASKFORREBOOT -eq 1 -o -e /run/reboot-required ]; then
		wrapTxtFn "$(_ main.reboot_question)"
		centerTxtFn "$WRAPPEDTXT"
		valignTxtFn "$CENTEREDTXT"
		showConfirmDlg "$ALIGNEDTXT";
	
		# 0: Do reboot
		# 1: Don't reboot
		case "$?" in
			0)
				DOREBOOT=1;
			;;
			1)
				:
			;;
		esac
	fi
	
	# Clear FS and MEM caches
	#clrFSCacheFn;
	#clrMemCacheFn;
	if [ $DOREBOOT -eq 1 ]; then
                sync
		reboot
	fi
	exit 0
}

function showMainMenuDlg() {

	ITEMS="";
	LEVEL="";
	ADD=".";
	CPATH=$(_ main.title);
	
	# Do different things depending on which level we are
	if [ $1 -gt 0 ]; then
		# Show descendant
		LEVEL="$2";
		ADD=".";
	fi

	# Prepare path
	if [ $# -gt 2 ]; then
		CPATH=$3;
	fi
	
	# Trim CPATH
	trimLnFn $CPATH
	CPATH=$TRIMMEDLN;

	# Draw showMainMenuDlg
	IFS=$'\n';
	
	# Get all sub-items that corresponding to the level we are currently
	ITEMS=$(grep "^$LEVEL$ADD[0-9]*:" $BASEPATH/struct | cut -f 2 -d:);

	# Clear caches need by previous function
	#clrMemCacheFn;
	
	# Create main menu

	# If a certain menu items has no subitems, than we've reach of final function we want to execute
	if [ -z "$ITEMS" ]; then
		
		# Grab the system name of the module we want to execute
		SPECIFICLEVEL=${LEVEL:0:-1};
		MODULE=$(grep ^$SPECIFICLEVEL: $BASEPATH/struct | cut -f2 -d:);

		# Include the module we want to execute
		source $BASEPATH/modules/$MODULE/main
		
		# Change the dialog title to reflect the current module
		TITLE="[${CPATH% > *} > $(_ $MODULE.name)]"
		
                killLoader

		# Open the modules gui function
		showGUIFn;
		
		# When we're done, show the main menu again
		IFS=$'\n';
		showMainMenuDlg $(($1-1)) ${LEVEL:0:-2} ${CPATH% > *};
	else
		MENU="";
		I=1;
		for ITEM in ${ITEMS[@]}; do
			MENU+="$I"$DEFAULTDELIMITER"$(_ ${ITEM}.name)"$DEFAULTCOLSEP"-"$DEFAULTCOLSEP"$(_ $ITEM.description)"$DEFAULTDELIMITER;
			I=$(($I+1));
		done;
		
		IFS=$DEFAULTDELIMITER;
		# Set the title to the appropriate menu level we're in
		TITLE="["$CPATH"]"

		# Show the main menu
		if [ $1 -eq 0 ]; then
			showMenuDlg "" "$MENU" 10 14 $(($DEFAULTWIDTH+35)) $(_ dialog.select) $(_ dialog.exit);
		else
			showMenuDlg "" "$MENU" 10 14 $(($DEFAULTWIDTH+35))
		fi
			
		# What there a button pressed?
		#  1: Button
		#  0: Item
		CODE=$?
		if [ $CODE -eq 1 ]; then
			# Which button was pressed?
			#  0: Close
			#  1: Select
			if [ ! $1 -eq 0 ]; then
				IFS=$'\n';
				showMainMenuDlg $(($1-1)) ${LEVEL:0:-2} ${CPATH% > *};
			fi
		elif [ $CODE -eq 0 ]; then 
			IFS=$'\n';
			MODULE=$(grep "^$LEVEL$RETURN*:" $BASEPATH/struct | cut -f 2 -d:)
			
			showMainMenuDlg $(($1+1)) $LEVEL$RETURN$ADD  "$CPATH > $(_ $MODULE.name)";			
		fi;
	fi;
}

#mountpoint -q /boot || { mount /boot; touch /run/xbian-config.umount; }

if [ $# -eq 0 -o "$1" = goto ]; then

	#|------------------------------------|
	#|              GUI Mode              |
	#|------------------------------------|
	echo $$ >> /run/lock/xbian-config.gui

	LOADER=0;
	while ! pgrep dialog > /dev/null; do 
		for a in \\ \| \/ -; do
			{ ! pgrep dialog > /dev/null && echo -n -e \\r$a; } \
				|| break
		done
	done &
	LOADER=$!

	#|------------------------------------|
	#|          Include files             |
	#|------------------------------------|

	# Common xbian-config functions
	source $BASEPATH/functions/packages

	# Pre-requirements
	source $BASEPATH/prereqs

	# Standard dialogs
	source $BASEPATH/functions/dialogs

	# Text markup
	source $BASEPATH/functions/markup

	# System functions
	source $BASEPATH/functions/system

	# Language functions
	source $BASEPATH/functions/language
	
	#|------------------------------------|
	#|          Global variables          |
	#|------------------------------------|
        if [ "$1" == goto ]; then
                . $BASEPATH/modules/$2/main
                showGUIFn
                killLoader
                exit 
        fi

	# Current dialog title
	TITLE="[$_TITLE]"

	#Run script inside screen, so it's doesn't fill the whole terminal history
	#SCREEN=$(screen -r | grep "Attached" | wc -l);
	#if [ $SCREEN -eq 0 ]; then
	#	`screen $0`
	#else
		showMainMenuDlg 0 "";
	#fi
	eval $(echo "sed -i '/$$/d' /run/lock/xbian-config.gui")
else
	#|------------------------------------|
	#|              CLI Mode              |
	#|------------------------------------|

	#|------------------------------------|
	#|          Include files             |
	#|------------------------------------|

        echo $$ >> /run/lock/xbian-config

	# System functions
	source $BASEPATH/functions/system
	#clrMemCacheFn;
	
	export GUIMODE=0;
	# Check xbian-config was opened using arguments
	MODULE=$1;
	[ $MODULE = "--help" -o $MODULE = "-h" ] && MODULE=help
	if [ $MODULE == "reboot" ]; then
		[ -n "$2" ] && [ "$2" -eq 1 ] && { touch /var/run/reboot-required; exit 0; }
		if [ -f /var/run/reboot-required ]; then
			{ pgrep dpkg > /dev/null|| pgrep apt-get >/dev/null || ps x | grep -v "grep"| grep -q "/usr/bin/unattended-upgrade" ; } && exit 0
			echo 1;
		else
			echo 0;
		fi;
	elif [ -f $BASEPATH/modules/$MODULE/main ]; then
                source $BASEPATH/modules/$MODULE/main
		shift;
		# If the module was called with arguments
		if [ $# -gt 0 ]; then
			# Check if it's a valid argument
			case "${ARGUMENTS[@]}" in 
				*"$1"*)
					# Spaces allowed for xbiancopy arguments
					[ "$MODULE" = "xbiancopy" ] && IFS=$'\n'
					# Quotation marks to preserve newlines
                                        showCMDFn "$@"
				;;
				*)
					[ -z "txt" ] && echo "Available arguments for module '$MODULE' are:";
					echo ${ARGUMENTS[@]};
				;;
			esac
		else
			[ -z "txt" ] && echo "Available arguments for module '$MODULE' are:";
			echo ${ARGUMENTS[@]};
		fi
	fi
        eval $(echo "sed -i '/$$/d' /run/lock/xbian-config")
fi

exit 0
