#!/bin/bash

_toolchain_build_menu(){
	[ "$loadprofile" == "yes" ] && load_config

	selected=$(
	"$gui" "$st_" "$bt_" "$title_" --no-cancel --title " -[ $txt_bmenu_title ]- " --menu "_________________________________________________________ \n $txt_bmenu_user = $(whoami)\n Toolchain       = $_toolchainname\n $txt_bmenu_comp = $_compiler""gcc\n $txt_bmenu_debu = CPU-Threads($(CPUS)) SVN($(REVISION)) SCRIPT($SIMPLEVERSION)\n $txt_bmenu_use  = $(echo $USESTRING| sed -e 's/^[ \t]*//')\n _________________________________________________________ \n" 22 65 10 BUILD "$txt_bmenu_build" CONFIGURE "$txt_bmenu_config" UPDATE "$txt_bmenu_update" BACKUP "$txt_bmenu_backup" LOAD_PROFILE "$txt_bmenu_profile" SAVE_PROFILE "$txt_bmenus_profile" SHOW_BUILDLOG "$txt_bmenu_log" EDIT_CONF_DIR "Oscam config PATH" BACK "$txt_bmenu_back" EXIT "$txt_firstmenu_exit")
	[ $? = 255 ] && _toolchain_build_menu

	case $selected in
		BUILD)
						_gui_build;;
		CONFIGURE)
						_toolchain_config_menu;;
		UPDATE)
						tcupdate "$_toolchainname" "" "" "2"
						_toolchain_build_menu;;
		BACKUP)
						tcupdate "-b" "$_toolchainname" "" "1"
						_toolchain_build_menu;;
		EDIT_CONF_DIR)
						_gtedit
						_toolchain_build_menu;;
		SHOW_BUILDLOG)
						_sz;
						if [ -f "$workdir/lastbuild.log" ]
						then
							"$gui" "$st_" "$bt_" "$title_" --textbox "$workdir/lastbuild.log" "$_lines" "$_cols"
						fi
						_toolchain_build_menu;;
		LOAD_PROFILE)
						_load_profile;;
		SAVE_PROFILE)
						_save_profile;;
		BACK)
						_toolchain_main_menu;;
		EXIT)
						bye
						exit;;
	esac

	_toolchain_build_menu
}

_toolchain_config_menu(){
	[ "$loadprofile" == "yes" ] && load_config

	selected=$(
	"$gui" "$st_" "$bt_" "$title_" --no-cancel --title " -[ $txt_config_menu ]- " --menu " ADDONS :\n $(e_addons)\n\n PROTOCOLS :\n $(e_protocols)\n\n READERS :\n $(e_readers)\n\n CARD_READERS :\n $(e_card_readers)\n\n USE VARIABLES :\n $(echo $USESTRING| sed -e 's/^[ \t]*//')\n\n" 29 75 6 BACK "$txt_back_build" OSCAM_MODULE "$txt_module_configure" OSCAM_EXTRA "$txt_oscam_extra" BUILD_EXTRA "$txt_build_extra" SELECT_STAPI "select stapi" RESET "$txt_build_reset")
	[ $? = 255 ] && _toolchain_config_menu

	case $selected in
		BACK)
						save_config
						_toolchain_build_menu;;
		OSCAM_EXTRA)
						_oscam_extra_menu;;
		BUILD_EXTRA)
						_build_extra_menu;;
		OSCAM_MODULE)
						eval "$svndir/config.sh -g" 2>/dev/null
						save_config;;
		SELECT_STAPI)
						_stapi_select;;
		RESET)
						_reset_config
						load_config
						_toolchain_config_menu;;
	esac

	_toolchain_config_menu
}

_toolchain_main_menu(){
	_fill_tc_array
	IFS="#"
	COUNT=0
	MENU_OPTIONS="BACK#$txt_back_main#"
	counter

	if [ "$systype" == "ok" ]
	then
		MENU_OPTIONS+="ADD#$txt_menu_builder2#"
		counter
		MENU_OPTIONS+="CREATE#$txt_menu_builder5#"
		counter
		[ "$tcempty" == "0" ] && MENU_OPTIONS+="REMOVE#$txt_menu_builder3#" && counter
	fi

	MENU_OPTIONS+="native#$txt_menu_builder4 $(hostname)-$(uname -m)#"
	counter

	if [ "$tcempty" == "0" ]
	then
		for i in "${INST_TCLIST[@]}"
		do
			if [ ! "$i" == "native" ]
			then
				unset _self_build
				source "$tccfgdir/$i"
				if [ "$systype" == "ok" ]
				then
					MENU_OPTIONS+="$_toolchainname#$_description#"
					counter
				elif [ "$_self_build" == "yes" ]
				then
					MENU_OPTIONS+="$_toolchainname#$_description#"
					counter
					
				fi
			fi
		done
	fi

	MENU_OPTIONS+="EXIT#$txt_firstmenu_exit#"
	counter
	out=$(
	"$gui" "$st_" "$nc_" "$bt_" "$title_" --help-button --help-label INFO --title "-[ Toolchain $txt_menu ]-" --menu "$txt_main_revision$(REVISION)" "${COUNT+8}" 75 0 ${MENU_OPTIONS})
	IFS=$OIFS
	first=$(echo "$out" | awk '{printf $1}')
	tc_info=$(echo "$out" | awk '{printf $2}';)

	case $first in
		EXIT)
				bye;;
		BACK)
				_select_menu;;
		ADD)
				_toolchain_add_menu;;
		CREATE)
				tcupdate "-c" "" "" "1"
				_toolchain_main_menu;;
		REMOVE)
				_toolchain_remove_menu;;
		HELP)
				if [ -f "$tccfgdir/$tc_info" ]
				then
					source "$tccfgdir/$tc_info"
					"$gui" "$st_" "$nc_" "$bt_" "$title_" "$ib_" "$_tc_info" $((_tc_infolines + 5)) 65
					sleep 5
				fi
				_toolchain_main_menu;;
		*)
				[ -f "$tccfgdir/$first" ] && stapi_allowed="" && source "$tccfgdir/$first" || exit
				loadprofile="yes"
				_toolchain_build_menu "$first";;
		esac
}

get_toolchain_config(){
	get_toolchain_list
	for ((i=0;i<${#toolchain_list[@]};i++))
	do
		[ "${toolchain_list[$i]}" == "$1" ] && source "$sdir/toolchain.cfgs/$1"
	done
}

_load_toolchain(){
	[ ! -z "$1" ] && source "$tccfgdir/$1"
	dln="$(decode "$_t1e")$(decode "$_toolchainfilename")"
	tc_dl="$dldir/$dln"
	[ -f "$dln" ] && rm -rf "$dln"
	clear
	printf "$c_l"
	ologo
	_nl
	printf "$p_l  load only"
	_nl
	printf "$w_l  Toolchain   :$y_l $dln"
	printf "$w_l  download    :$g_l "
	_pget
}

get_toolchain_list(){
	[ -d "$sdir/toolchain.cfgs" ] && cd "$sdir/toolchain.cfgs" || printf " please fix $sdir/toolchain.cfgs"
	toolchain_list=()
	toolchain_list+=('native')
	toolchain_list+=(*)
	cd "$workdir"
}

_console_extract_toolchain(){
	[ -d "$tcdir/$_toolchainname" ] && rm -rf "$tcdir/$_toolchainname"
	mkdir "$tcdir/$_toolchainname"
	cd "$tcdir/$_toolchainname"
	xz -d "$tc_dl" -c | tar -x
	printf "\r$w_l    $txt_extracting :$g_l$txt_done!                             \n\n"
}

_toolchain_check(){
	clear
	printf "$w_l"
	s3logo
	headervars=( crypto.h pcsclite.h libusb.h pthread.h )
	[ -f "$tccfgdir/$1" ] && source "$tccfgdir/$1"

	if [ -d "$tcdir/$1/bin" ]
	then
		cd "$tcdir/$1/bin"
	else
		printf "$r_l  $txt_error:$y_l $1$w_l Toolchain $txt_n_installed""$rs_"
		_nl
		exit
	fi

	printf "$w_l  Compiler Info -----> $C$1$w_l\n  ====================\n"

	if [ -z "$sysroot" ] && [ ! "$1" == "native" ]
	then
		compilername="$_compiler""gcc"
		[ ${#_realcompiler} -gt 4 ] && compilername="$_realcompiler"
		version=$("./$compilername" -dumpversion)
		machine=$("./$compilername" -dumpmachine)
		[ "$_androidndkdir" == "1" ] && sr="$tcdir/$1/sysroot" || sr=$("./$compilername" -print-sysroot 2>/dev/null)
		sysroot=${sr#"$tcdir/$1/bin/../"}
		compilerpath=$(realpath ./$compilername)
		printf "$w_l  GCC Version :$y_l $version\n"
		printf "$w_l  GCC Binary  :$y_l $machine""-gcc $([ -L "./$compilername" ] && printf "$p_l(${compilerpath#"$tcdir/$1/"})")\n"
		printf "$w_l  GCC Sysroot :$y_l $sysroot\n"
		[ -z "$sysroot" ] && sysroot="$r_l$txt_too_old\n"
		cd "$sr"
		for e in "${headervars[@]}"
		do
			temp=$(find * |grep -m1 "$e")
			[ ${#temp} -gt 8 ] && printf "$w_l  Header File :$y_l $e$g_l\t$txt_found\n" || printf "$w_l  Header File :$y_l $e$r_l\t($txt_not_found)\n"
		done
	fi

	if [ "$1" == "native" ]
	then
		printf "$w_l  GCC Version :$y_l $(gcc --version |head -n 1 )"
		printf "$w_l  GCC Binary  :$y_l $(gcc -dumpmachine )"
	fi

	printf "\n$w_l  Sysroot config ----> $C$_sysroot$w_l\n  ====================\n"

	[ "$1" == "native" ] && cd "$_sysroot" || cd "$tcdir/$1/$_sysroot"

	for e in "${headervars[@]}"
	do
		temp=$(find * |grep -m1 "$e")
		[ ${#temp} -gt 8 ] && printf "$w_l  Header File :$y_l $e$g_l\t$txt_found\n" || printf "$w_l  Header File :$y_l $e$r_l\t($txt_not_found)\n"
	done

	pkg=$(find * |grep -m1 "pkgconfig")
	if [ ${#pkg} -gt 0 ]
	then
		[ "$1" == "native" ] && cd "$_sysroot/$pkg" || cd "$tcdir/$1/$_sysroot/$pkg"
		printf "\n$w_l  Library config ----> $C$_sysroot/$pkg$w_l\n  ====================\n"
		for f in *.pc
		do
			content=$(cat "$f") && na=$(echo "$content" | grep 'Name:' | sed -e "s/Name: //g") && ver=$(echo "$content" | grep 'Version:' | sed -e "s/Version: //g")
			sp1=$(printf '%*s' $((20-${#f})) | tr ' ' ' ') && sp2=$(printf '%*s' $((20-${#na})) | tr ' ' ' ')
			[ ${#content} -gt 0 ] && printf "$w_l  Library Config :$y_l "$f"$sp1$g_l$txt_found\t$p_l$na$sp2$ver\n" || printf "$w_l  Library Config :$y_l "$f"$sp1$r_l($txt_not_found)\n"
		done
	else
		printf "\n$w_l  Library config ----> $C no libraries found in pkgconfig$w_l\n  ====================\n"
	fi

	printf $re_
	exit
}

_toolchain_repair(){
	clear
	printf "$w_l\n"
	s3logo
	cd $dldir
	zzusatz=0
	szusatz=0
	[ -f "$tccfgdir/$1" ] && source "$tccfgdir/$1"

	fn=$(echo $_md5sum |awk '{ printf $2 }')

	if [ ${#_md5sum} -lt 1 ]
	then
		printf $w_l"  md5sum in $Y$1$w_l config $R$txt_not_found$W\n\n"
		exit
	fi

	if [ -f $fn ]
	then
		md5file=$(mktemp)
		printf "$_md5sum\n" > $md5file
		answer=$(md5sum -c $md5file 2>&1)

		if [ "$answer" == "$fn: OK" ]
		then
			printf $w_l"  Toolchain md5 check :$g_l ok\n"
			printf $w_l
			tc_dl="$dldir/$fn"
			printf $w_l"  Toolchain repair    :$y_l $txt_wait$g_l"
			_console_extract_toolchain
			tput cup 10 0
			printf $w_l"  Toolchain repair    :$g_l ok                           \n\n"
		else
			printf $w_l"  Toolchain md5 check :$r_l fail\n"
			zzusatz=-1
			szusatz=8
			printf $w_l"  Toolchain download  :$g_l\n"
			dln=$fn
			_pget
			tput cup 10 22
			printf $w_l":$g_l ok                                       \n"
			printf $w_l"  Toolchain repair    :$y_l $txt_wait$g_l"
			_console_extract_toolchain
			tput cup 10 23
			printf "$g_l ok                        \n"
			tput cup 11 23
			printf "$g_l ok                        \n"
			_nl
			exit
		fi

	else
		printf $w_l"  Toolchain Filename :$y_l $fn\n"
		printf $w_l"  Toolchain download :$g_l"
		zzusatz=-1
		szusatz=7
		dln=$fn
		_pget
		tput cup 10 22
		printf "$g_l ok                                       \n"
		sleep 1
		printf $w_l"  Toolchain repair   :$y_l $txt_wait$g_l"
		zzusatz=2
		szusatz=7
		_console_extract_toolchain
		tput cup 10 22
		printf "$g_l ok                                       \n"
		tput cup 11 22
		printf "$g_l ok                                       \n"
		_nl
		exit
	fi
}

_toolchain_add_menu(){
	_fill_tc_array
	_init_menu

	for i in "${MISS_TCLIST[@]}"
	do
		if [ ! "$i" == "native" ]
		then
			source "$tccfgdir/$i"
			MENU_OPTIONS+="$_toolchainname#$_description#"
			counter
		fi
	done

	MENU_OPTIONS+="EXIT#$txt_menu_builder1#"
	counter

	out=$(
	"$gui" "$st_" "$nc_" "$bt_" "$title_" --help-button --help-label INFO --title "-[ $txt_add_menu ]-" --menu "$txt_main_revision$(REVISION)" "${COUNT+8}" 75 0 ${MENU_OPTIONS[@]})
	IFS=$OIFS
	first=$(echo "$out" | awk '{printf $1}')

	case $first in
		EXIT)
				bye;;
		BACK)
				_toolchain_main_menu;;
		*)
				_toolchain_gui_install
				_toolchain_main_menu;;
	esac
}

_toolchain_remove_menu(){
	_fill_tc_array
	_init_menu
	if [ "$tcempty" == "0" ]
	then
		for i in "${INST_TCLIST[@]}"
		do
			if [ ! "$i" == "native" ]
			then
				source "$tccfgdir/$i"
				MENU_OPTIONS+="$_toolchainname#$_description#"
				counter
			fi
		done
	fi

	MENU_OPTIONS+="EXIT#$txt_menu_builder1#"
	counter

	out=$(
	"$gui" "$st_" "$nc_" "$bt_" "$title_" --title "-[ $txt_remove_menu ]-" --menu "$txt_main_revision$(REVISION)" "${COUNT+8}" 75 0 ${MENU_OPTIONS})
	IFS=$OIFS
	first=$(echo "$out" | awk '{printf $1}')

	case $first in
		EXIT)
				bye;;
		BACK)
				_toolchain_main_menu;;
		*)
				[ -d "$tcdir/$first" ] && rm -rf "$tcdir/$first"
				_toolchain_main_menu;;
	esac
}

_toolchain_gui_install(){
	[ -d "$tcdir/$first" ] && rm -rf "$tcdir/$first" && printf "$txt_delete $tcdir/$first"
	mkdir "$tcdir/$first"
	cd "$tcdir/$first"
	source "$tccfgdir/$first"
	tcname="$(decode "$_t1e$_toolchainfilename")"
	stcname="$(decode "$_toolchainfilename")"

	if [ -f "$dldir/$tcname" ]
	then
		(xz -d "$dldir/$tcname" -c| tar -xv) |"$gui" "$st_" --title " -[ $txt_extracting ]- " "$pb_" 20 74
	else
		cd "$dldir"
		wget "$(decode "$_u1e")/$tcname" 2>&1 | stdbuf -o0 awk '/[.] +[0-9][0-9]?[0-9]?%/ { print substr($0,63,3) }' | "$gui" "$st_" "$bt_" "$title_" --title " -[ download ]- " --gauge "  $txt_loading $stcname $txt_wait" 6 74
		cd "$tcdir/$first"
		(xz -d "$dldir/$tcname" -c |tar -xv) |"$gui" "$st_" --title " -[ $txt_extracting ]- " "$pb_" 20 74
	fi
}