#!/bin/bash
#
# --- T2-COPYRIGHT-NOTE-BEGIN ---
# This copyright note is auto-generated by ./scripts/Create-CopyPatch.
# 
# T2 SDE: scripts/Config
# Copyright (C) 2004 - 2007 The T2 SDE Project
# Copyright (C) 1998 - 2003 ROCK Linux Project
# 
# More information can be found in the files COPYING and README.
# 
# This program 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; version 2 of the License. A copy of the
# GNU General Public License can be found in the file COPYING.
# --- T2-COPYRIGHT-NOTE-END ---

if [ -z "${lines:=$LINES}" -o -z "${columns:=$COLUMNS}" ] ; then
	if [ "$( type -p stty )" ] ; then
		lines="$(   stty size 2> /dev/null | cut -d' ' -f1 )"
		columns="$( stty size 2> /dev/null | cut -d' ' -f2  )"
	fi
	[ -z "$lines"   -o "$lines"   -le 0 ] 2> /dev/null && lines=24
	[ -z "$columns" -o "$columns" -le 0 ] 2> /dev/null && columns=80
fi

eval "$(egrep '^sdever=' scripts/parse-config)"

config=default
do_config_cycle=0
delete_mode=0
oldconfig=''
cfgtmpdir=''
profile=""

show_usage() {
	echo
	echo "Usage: $0 [ -delete | -oldconfig ] [ -cfg <config> ]"
	echo
	echo "Other options:"
	echo "	-profile	create a config.profile with profiling data"
	echo
}

while [ "$1" ] ; do
        case "$1" in
	    -cycle)	do_config_cycle=1 ; shift ;;
	    -delete)	delete_mode=1     ; shift ;;
	    -profile)	profile='-profile'        ; shift ;;
	    -oldconfig)	oldconfig='-oldconfig'    ; shift ;;
	    -cfg)	config="$2"       ; shift ; shift ;;

	    *)  show_usage
		exit 1 ;;
        esac
done

if [ -z "$config" ]; then
	show_usage
	exit 1
fi

if [ ! -d config/$config -a -n "$oldconfig" ]; then
	echo "Abort: -oldconfig is not supported for new configs"
	echo
	exit 1
fi

if [ $delete_mode = 1 ] ; then
	rm -rv config/$config
	exit $?
fi

cfgtmpdir=src/$config

if [ $do_config_cycle = 0 ] ; then
	rm -rf $cfgtmpdir
	mkdir -p $cfgtmpdir	# src

	if [ -z "$oldconfig" -a ! -f src/confdialog.bin ] ; then
		echo "Creating confdialog tool."
		command="gcc misc/confdialog/*.c `
			`-Imisc/confdialog -lncurses -o src/confdialog.bin"
		echo "$command"
		if ! eval "$command.$$"; then
			echo "Compilation of the dialog tool failed, ncurses-devel missing?"
			exit 1
		fi
		mv src/confdialog.bin.$$ src/confdialog.bin
	fi

	# don't accept Ctrl-C because it destroy the configurations
	trap '' INT

	if [ -d config/$config ]; then
		echo "Backing up existing config/$config/* ..."
		mkdir -p $cfgtmpdir/backup
		cp -a config/$config/* $cfgtmpdir/backup
		if [ $? -ne 0 ]; then
			echo "Backup failed, aborting."
			exit 1
		fi
	fi

	echo "T2 $sdever configuration ..."
	while "$0" -cfg $config $oldconfig $profile -cycle ; do : ; done

	trap INT

	exit 0
fi

echo "Building src/luabash.so."
rm -rf src/luabash.so
make --no-print-directory -C misc/luabash X_OUTTOP=$PWD/src install

if [ ! -f src/luabash.so ]; then
	echo "Error building the LUA bash accelerator."
	exit 1
fi

if ! enable -f src/luabash.so luabash; then
	echo "Failed to enable the LUA bash accelerator"
	exit 1
fi

luabash load scripts/config-functions.lua || exit 1

if [ -z "$profile" ]; then
	bprof() { :; }
	bprof_print() { :; }
else
	if [ ! -f src/bash_profiler.so -o misc/tools-source/bash_profiler.c -nt src/bash_profiler.so ]; then
		echo "Building src/bash_profiler.so."
		gcc -shared -fPIC -Wall -o src/bash_profiler.so misc/tools-source/bash_profiler.c || exit 1
	fi
	enable -f src/bash_profiler.so bprof || exit 1
	bprof_print() {
		local cprof=$cfgtmpdir/config.profile
		bprof all print >> $cprof
		awk '
			$4 == "profiled" { next; }
			$4 != "main" { count["profiled"]+=$1; time["profiled"]+=$2; }
			{ count[$4]+=$1; time[$4]+=$2; }
			END {
				for (id in count)
					printf "%7d %7Ld %10.3f %s\n", count[id], time[id], time[id]/count[id], id;
			}
		' < $cprof | sort -n -k2 > $cprof.new
		mv $cprof.net $cprof
	}
fi

bprof main start

. scripts/config-functions.in
arch=`uname -m | uname2arch`
current="" ; export SDECFG_ARCH="$arch" ; export SDECFG_EXPERT=0
menu_this=0 ; menu_current=0 ; menu_counter=0
menu_stack=x ; menu_back=-1 ; menu_backpos=-1

set -e
mkdir -p config/$config
touch config/$config/{config,packages}
set +e

configtitle="$(printf ' %-50s %6s active packages ]' \
	"T2 $sdever Configuration - $config" \
	"[ $(echo `grep '^X' config/$config/packages | wc -l`)" )"

bprof main stop
# NOTE: ROCKCFG -> SDECFG automatized convertion
grep -q 'ROCKCFG' ./config/$config/config && 
	sed -i -e 's,ROCKCFG,SDECFG,g' ./config/$config/config

. ./config/$config/config
bprof main start

rm -f $cfgtmpdir/config.{dialog,data,help}
touch $cfgtmpdir/config.{dialog,data,help}
echo -e "#\n# T2 $sdever Config File\n#" > config/$config/config
spacer="" ; expert=0 ; tabspace="5" ; tabspace_list=""
commentnr=0 ; editfilenr=0

bprof mkpkglist start
cmd="./scripts/Create-PkgList"
cmd="$cmd $SDECFG_ARCH"

if [ "$cmd" != "`cat $cfgtmpdir/config.pcache.cmd 2> /dev/null`" ] ; then
	eval "$cmd" | tee $cfgtmpdir/config.pcache.data > config/$config/packages
	echo "$cmd" > $cfgtmpdir/config.pcache.cmd
else
	cat $cfgtmpdir/config.pcache.data > config/$config/packages
fi
bprof mkpkglist stop

# Create lists of .in files
create_dot_in_lists

export SDECFG_ID="$sdever"; pkgin; . scripts/config.in; pkgout
echo "export SDECFG_ID='$SDECFG_ID'" >> config/$config/config
rm -f $cfgtmpdir/*.tmp

cut -f1,2,4,5,8- -d' ' config/$config/packages | sed 's, [^ ]*$,,' | \
tr ' ' '\t' | expand -t2,15,35, > $cfgtmpdir/packages.txt

configtitle="$(printf ' %-50s %6s active packages ]' \
	"T2 $sdever Configuration - $config" \
	"[ $(echo `grep '^X' config/$config/packages | wc -l`)" )"

bprof main stop

if [ -z "$oldconfig" ] ; then
    eval "./src/confdialog.bin --title 'Build Config' \
	--backtitle '$configtitle' \
	--menu 'Arrow keys navigate the menu.  Press <Enter> to activate menu items.  Highlighted letters are hotkeys.' \
	$(( $lines - 4 )) $(( $columns - 5 )) $(( $lines - 12 )) \
	'$current' `tr '\n' ' ' < $cfgtmpdir/config.dialog`" 2> $cfgtmpdir/config.out
    returncode=$? ; item="`cat $cfgtmpdir/config.out`"
else
    returncode=1
fi

bprof main start

[ "$returncode" = 1 -a "$menu_back" -ne -1 ] && returncode="menu-back"

case "$returncode" in
	0|6)
		command="`grep "^$item	" $cfgtmpdir/config.data | cut -f2-`"
		{ echo -e "\n# Remember menu position:\ncurrent='$item'"
		echo -e "\n# Remember sub-menu:\nmenu_current='$menu_current'"
		echo -e "\n# Execute this config command:\n$command"
		} >> config/$config/config
		;;
	menu-back)
		{ echo -e "\n# New menu position:\ncurrent='$menu_backpos'"
		echo -e "\n# New sub-menu:\nmenu_current='$menu_back'"
		} >> config/$config/config
		;;
	1|255)
		rm -rf $cfgtmpdir
		echo "New config written to config/$config/*."
		echo "Cleaning up. Configuration finished."
		bprof main stop
		bprof_print
		exit 1 ;;
	2)
		tempitem=$item
		item=$(echo $item | cut -f1 -d' ')  # dialog(1) bug?
		{ echo -e "\n# Remember menu position:\ncurrent='$item'"
		echo -e "\n# Remember sub-menu:\nmenu_current='$menu_current'"
		} >> config/$config/config

		get_help $item > $cfgtmpdir/config.dialog

		bprof main stop
		./src/confdialog.bin --title 'T2 Config - Help' \
			--backtitle "T2 $sdever Configuration" \
			--textbox $cfgtmpdir/config.dialog \
			$(( $lines - 4 )) $(( $columns - 5 ))
		bprof main start
		;;
	*)
		echo "unknown returncode: $returncode"
		bprof main stop
		bprof_print
		exit 1 ;;
esac

bprof main stop
bprof_print

exit 0
