package boilertpl

const (
	ScriptCommonName = "script-common"
	ScriptCommonPath = ".boilerplate/_common.sh"
	ScriptCommonData = `
# First argument is a color number; the remainder are things to be echoed.  If stdout is a terminal and that terminal
# supports colors, echo those things in the given color; otherwise, echo them without color-related control sequences.
_colorize() {
    local COLOR="$1"
    shift
    if test -t 1; then
        local NCOLORS="$(tput colors)"
        if test -n "$NCOLORS" && test "$NCOLORS" -ge 8; then
            echo "$(tput setaf $COLOR)$@$(tput setaf sgr0)"
        else
            echo "$@"
        fi
    else
        echo "$@"
    fi
}

_black()   { _colorize 0 "$@"; }
_red()     { _colorize 1 "$@"; }
_green()   { _colorize 2 "$@"; }
_yellow()  { _colorize 3 "$@"; }
_blue()    { _colorize 4 "$@"; }
_magenta() { _colorize 5 "$@"; }
_cyan()    { _colorize 6 "$@"; }
_white()   { _colorize 7 "$@"; }
`

	ScriptCIName = "script-ci"
	ScriptCIPath = ".boilerplate/ci.sh"
	ScriptCIData = `
#!/usr/bin/env bash
set -euf -o pipefail -x

. .boilerplate/lint.sh
. .boilerplate/test.sh
. .boilerplate/build.sh
`

	// TODO:
	//  - Add 'vendorcheck -u' (check for unused, vendored packages)!
	//  - Fix and re-enable the "don't link the testing package" check below.
	ScriptLintName = "script-lint"
	ScriptLintPath = ".boilerplate/lint.sh"
	ScriptLintData = `
#!/usr/bin/env bash
set -euf -o pipefail -x

nonfmt="$(go fmt ./...)"
if [ -n "${nonfmt}" ]; then
	echo "${nonfmt}" | sed -e 's/^/non-gofmt code: /'
	false
fi

# -t: also check dependencies of test files
vendorcheck -t ./...

errcheck {{if .Global.Go.LintErrcheckIgnoreTests}}-ignoretests {{end}}./...

go vet ./...

{{if not .Global.Go.LintGolintDisabled}}
{{- if .Global.Go.LintGolintExcludeGenerated -}}
find . \( -not \( -ipath './vendor' -o -ipath './Godeps/_workspace/src' -o -iname '_*' \) -o -prune \) -type f -iname '*.go' \( -not -iname '*.pb.go' \) -print0 | xargs -0 -n1 golint -set_exit_status
{{- else -}}
golint -set_exit_status ./...
{{- end -}}
{{end}}
`

	// TODO: move 'tags' var definition to mantafile, since it is per-variant!

	/*
	   # # # @KK: Temporarily disable this check until it can be made more sophisticated.  (It makes it impossible to share code
	   # # # between the test code in two different packages!)
	   # # Lint: make sure that the "testing" package is not imported by non-test code.
	   # ! (go list -f '{{range .Deps}}{{printf "%q %q\n" $.ImportPath .}}{{end}}' ./... | grep '"testing"')
	*/

	ScriptTestName = "script-test"
	ScriptTestPath = ".boilerplate/test.sh"
	ScriptTestData = `
#!/usr/bin/env bash
set -euf -o pipefail -x

tags="netgo" # XXX:

. "$(dirname "$0")"/_common.sh

# Run tests.
go test  -tags "$tags" ./...
{{if not .Global.Go.UnsafeDataRaceDetectorDisabled -}}
go test  -tags "$tags" -race ./...
{{- else -}}
_red "boilerplate-gen: [UNSAFE] This project has explicitly disabled the data race detector."
{{end -}}
`

	// ** The following line of desired output:
	// for cmd in $(go list -f '{{if eq .Name "main"}}{{.ImportPath}}{{end}}' ./...); do
	// ** Becomes the following line of this template after escaping the template delimiters in it:
	// for cmd in $(go list -f '{{"{{"}}if eq .Name "main"{{"}}{{"}}.ImportPath{{"}}{{"}}end{{"}}"}}' ./...); do

	// tags: `{{.Global.Go.Tags | join ","}}`
	ScriptBuildName = "script-build"
	ScriptBuildPath = ".boilerplate/build.sh"
	ScriptBuildData = `
#!/usr/bin/env bash
set -euf -o pipefail -x
{{if .Global.BinaryProduct -}}

tags="netgo"  # XXX:

# Remove all compiled packages - this is required to make the netgo build tag
# work with go1.4's definition of go build's -a flag.
find "$(go env GOROOT)/pkg/$(go env GOOS)_$(go env GOARCH)" -name '*.a' -type f -delete
go install -a -tags "${tags}" std

# Find the path where common/golibs/bininfo will be linked - this changes when
# the vendor experiment is active.
bininfo="code.justin.tv/common/golibs/bininfo"
bininfo="$(go list "./vendor/$bininfo" || echo "$bininfo")"

# The format for -ldflags -X changed with go1.5 (when the linker command name
# changed from 5l/6l/8l/etc to link). go1.4 and earlier use a space between
# symbol name and value; go1.5 and later use an equals sign.
xsep="$(go tool -n link &>/dev/null && echo '=' || echo ' ')"

# We need to remove a prefix from the paths stored in the DWARF info to allow
# annotating source code with tools like pprof even when it's not at the same
# absolute path we used during the build.
#
# Find which GOPATH entry applies to the root of this directory, trim it (and
# the /src segment that follows) from all filenames.
rootpkg="$(go list -e .)"
trimpath="$(echo $PWD | head -c $((${#PWD}-${#rootpkg})) | sed -e 's,/*$,,')"

# Compile all commands.
for cmd in $(go list -f '{{"{{"}}if eq .Name "main"{{"}}{{"}}.ImportPath{{"}}{{"}}end{{"}}"}}' ./...); do

	# Build IDs are standard practice in large software distributions; see
	# Roland McGrath's description here:
	# https://fedoraproject.org/wiki/Releases/FeatureBuildId.
	#
	# Some linkers are able to generate good build IDs automatically based on
	# some parts of the linked executable. Go's linker doesn't do that for us,
	# but it allows us to specify our own. This is one of the first known uses
	# of build IDs in Go programs at Twitch (2016-03-07), so let's come up
	# with something good enough for now.
	#
	# The build IDs should be unique for each executable shipped to production
	# hardware. We can get that by hashing the current git commit and the name
	# of the program, since these next few lines are the only way we build
	# production binaries for this repo and we only link each program once.
	#
	# We'd need something more if we started building and shipping race-
	# enabled versions of these programs, since the commit and program name
	# would match.
	#
	# This doesn't allow calculating the program name and commit if only the
	# build ID is known. We can tackle that later.

	buildid="$( (echo $tags ; echo $GIT_COMMIT ; echo $cmd) | sha256sum | cut -c -64 )"
	if [ "${GIT_COMMIT}" != "${GIT_COMMIT%-dirty}" ]; then
		# Don't write a real-looking Build ID if the repo has local
		# modifications
        buildid="deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
	fi

	go install -v -tags "${tags}" \
		-asmflags "-trimpath ${trimpath}" \
		-gcflags "-trimpath ${trimpath}" \
		-ldflags "-X ${bininfo}.revision${xsep}${GIT_COMMIT} -B 0x$buildid" \
		-- "$cmd"
done
{{- end}}
`
)
