# Copyright 2012 The Go Authors.  All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

# These function names are also known to
# (and are the plan for transitioning to) run.go.

# helper (not known to run.go)
# group file list by packages and return list of packages
# each package is a comma-separated list of go files.
pkgs() {
	pkglist=$(grep -h '^package ' $* | awk '{print $2}' | sort -u)
	for p in $pkglist
	do
		echo $(grep -l "^package $p\$" $*) | tr ' ' ,
	done | sort
}

_match() {
	case $1 in
	*,*)
		#echo >&2 "match comma separated $1"
		first=$(echo $1 | sed 's/,.*//')
		rest=$(echo $1 | sed 's/[^,]*,//')
		if _match $first && _match $rest; then
			return 0
		fi
		return 1
		;;
	'!'*)
		#echo >&2 "match negation $1"
		neg=$(echo $1 | sed 's/^!//')
		if _match $neg; then
			return 1
		fi
		return 0
		;;
	$GOARCH|$GOOS)
		#echo >&2 "match GOARCH or GOOS $1"
		return 0
		;;
	esac
	return 1
}

# +build aborts execution if the supplied tags don't match,
# i.e. none of the tags (x or !x) matches GOARCH or GOOS.
+build() {
	if (( $# == 0 )); then
		return
	fi
	m=0
	for tag; do
		if _match $tag; then
			m=1
		fi
	done
	if [ $m = 0 ]; then
		#echo >&2 no match
		exit 0
	fi
	unset m
}

compile() {
	$G $D/$F.go
}

compiledir() {
	for pkg in $(pkgs $D/$F.dir/*.go)
	do
		$G -I . $(echo $pkg | tr , ' ') || return 1
	done
}

errorcheckdir() {
	lastzero=""
	if [ "$1" = "-0" ]; then
		lastzero="-0"
	fi
	pkgs=$(pkgs $D/$F.dir/*.go)
	for pkg in $pkgs.last
	do
		zero="-0"
		case $pkg in
		*.last)
			pkg=$(echo $pkg |sed 's/\.last$//')
			zero=$lastzero
		esac
		errchk $zero $G -D . -I . -e $(echo $pkg | tr , ' ')
	done
}

rundir() {
	lastfile=""
	for pkg in $(pkgs $D/$F.dir/*.go)
	do
		name=$(echo $pkg | sed 's/\.go.*//; s/.*\///')
		$G -D . -I . -e $(echo $pkg | tr , ' ') || return 1
		lastfile=$name
	done
	$L -o $A.out -L . $lastfile.$A
	./$A.out
}

rundircmpout() {
	lastfile=""
	for pkg in $(pkgs $D/$F.dir/*.go)
	do
		name=$(echo $pkg | sed 's/\.go.*//; s/.*\///')
		$G -D . -I . -e $(echo $pkg | tr , ' ') || return 1
		lastfile=$name
	done
	$L -o $A.out -L . $lastfile.$A
	./$A.out 2>&1 | cmp - $D/$F.out
}

build() {
	$G $D/$F.go && $L $F.$A
}

runoutput() {
	go run "$D/$F.go" "$@" > tmp.go
	go run tmp.go
}

run() {
	gofiles=""
	ingo=true
	while $ingo; do
		case "$1" in
		*.go)
			gofiles="$gofiles $1"
			shift
			;;
		*)
			ingo=false
			;;
		esac
	done

	$G $D/$F.go $gofiles && $L $F.$A && ./$A.out "$@"
}

cmpout() {
	$G $D/$F.go && $L $F.$A && ./$A.out 2>&1 | cmp - $D/$F.out
}

errorcheck() {
	zero=""
	if [ "$1" = "-0" ]; then
		zero="-0"
		shift
	fi
	errchk $zero $G -e $* $D/$F.go
}

errorcheckoutput() {
	zero=""
	if [ "$1" = "-0" ]; then
		zero="-0"
		shift
	fi
	go run "$D/$F.go" "$@" > tmp.go
	errchk $zero $G -e tmp.go
}

skip() {
	true
}
