#!/bin/bash
#
# Set up the control directory for a susetest based twopence
# script

if [ $# -lt 3 ]; then
	echo "Missing argument(s)" >&2
	echo "Usage: $0 <name> <nodesfile> <runcsript> [<instroot>]" >&2
	exit 1
fi

name=$1
nodesfile=$2
runscript=$3
instroot=$4

ctrldir=/var/lib/slenkins/twopence-$name
testdir=/usr/lib/twopence/$name

function do_mkdir {

	echo "== mkdir $*"
	for dir; do
		mkdir -m 755 -p "$instroot/$dir" || exit 1
	done
}

function do_install {

	declare -a args

	echo "== install $*"

	while [ $# -gt 1 ]; do
		args+=("$1")
		shift
	done
	destination=$1

	install "${args[@]}" "$instroot/$destination" || exit 1
}

function do_symlink {

	echo "== symlink $2 -> $1"

	if [ $# -ne 2 ]; then
		echo "do_symlink: need exactly two arguments" >&2
		exit 1
	fi

	case "$1" in
	/*) : ;;
	*)  # Symlink is already relative
	    echo "ln -sf \"$1\" \"$instroot$2\""
	    ln -sf "$1" "$instroot$2" || exit 1
	    return 0;;
	esac

	targ=$(echo "$1" | sed 's://*:/:g;s:^/::')
	link=$(echo "$2" | sed 's://*:/:g;s:^/::')

	echo "Turning absolute symlink into relative one"

	common=
	while true; do
		tgtnext=${targ%%/*}
		dstnext=${link%%/*}

		test "$tgtnext" = "$dstnext" || break

		common="$common/$tgtnext"
		targ=${targ#*/}
		link=${link#*/}

		if [ -z "$link" -o -z "$targ" ]; then
			echo "Link is a prefix of target, or vice versa" >&1
			exit 1
		fi

		echo "$common/{$targ -> $link}"
	done

	# Now count the number of directory components
	# remaining in the link name
	ndirs=0
	while true; do
		case $link in
		*/*)
			let ndirs++
			targ="../$targ"
			link="${link#*/}";;
		*)
			break;;
		esac
	done

	echo "Link has $ndirs more dir components"

	echo "ln -sf \"$targ\" \"$instroot$2\""
	ln -sf "$targ" "$instroot$2" || exit 1
}

do_mkdir $testdir
do_install -m 555 $runscript $testdir
do_symlink /usr/lib/susetest/twopence-run $testdir/control

do_mkdir $ctrldir/control/bin
do_install -m 444 "$nodesfile" $ctrldir/control
do_install -m 555 $runscript $ctrldir/control/bin/01_run.sh
