#!/bin/bash
# Copyright (C) 2006,2007 Lauri Leukkunen <lle@rahina.org>
# Licensed under GPL version 2

my_path=$_
if [ $(basename $my_path) != $(basename $0) ]; then
	my_path=$0
	if [ $(basename $my_path) = $my_path ]; then
		my_path=$(which $my_path)
	fi
fi


function usage()
{
	cat <<EOF
sb2-config - configure scratchbox2
Usage:
	sb2-config [OPTION]... [TARGETNAME]

Options:
    -d TARGETNAME     set default scratchbox2 target
    -l                list scratchbox2 targets
    -L TARGETNAME     show configuration log ('-' as target name refers to the
                      default target)
    -h                print this help
    -v                display version

Examples:
    sb2-config -d ARM
EOF
	exit 2
}

function version()
{
	cat $SBOX_DIR/share/scratchbox2/version
	exit 0
}

function list_targets()
{
	if [ ! -d $HOME/.scratchbox2 ]; then
		echo "$HOME/.scratchbox2 missing, create some targets with sb2-init!" >&2
		exit 1
	fi
	list=$(find $HOME/.scratchbox2/ -maxdepth 2 -mindepth 2 \
		-type f -and -name "sb2.config" 2>/dev/null)
	if [ $? != 0 ]; then
		echo "Error occured while getting list of targets" >&2
		exit 2
	fi
	if [ -z "$list" ]; then
		echo "No targets found, create some with sb2-init!" >&2
		exit 1
	fi
	for f in $list; do echo $(basename $(dirname $f)); done
}

function show_config_log()
{
	target=$1

	if [ "$target" == "-" ]; then
		# use default target
		if [ ! -f $HOME/.scratchbox2/config ]; then
			echo "default target has not been set!" >&2
			exit 1
		fi
		. $HOME/.scratchbox2/config
		target=$DEFAULT_TARGET
		echo "Configuration log of '$target'"
	fi

	if [ ! -d $HOME/.scratchbox2/$target ]; then
		echo "target $target does not exist!" >&2
		exit 1
	fi

	if [ ! -f $HOME/.scratchbox2/$target/sb2.config.d/CONFIG-LOG ]; then
		echo "target $target does not have a configuration log!" >&2
		exit 1
	fi
	# else log found

	cat $HOME/.scratchbox2/$target/sb2.config.d/CONFIG-LOG
	exit 0
}

function write_config()
{
	echo "
DEFAULT_TARGET=$DEFAULT_TARGET
" > $HOME/.scratchbox2/config
}

SBOX_DIR=$(readlink -f $(dirname $(readlink -f $my_path))/..)
WRITE_CONFIG=0

if [ $# == 0 ]; then
	# No parameters
	usage
fi

while getopts d:hlL:v foo
do
	case $foo in
	(d) DEFAULT_TARGET=$OPTARG
	    WRITE_CONFIG=1
	    ;;
	(h) usage ;;
	(l) list_targets ;;
	(L) show_config_log $OPTARG ;;
	(v) version ;;
	(*) usage ;;
	esac
done
shift $(($OPTIND - 1))

if [ $WRITE_CONFIG == 1 ]; then
	write_config
fi

