#!/usr/bin/env bash

# Copyright Istio Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This script runs can be used to emit (readable) compile tracing info when building go packages

# Before and after usage, `go clean -cache` is suggested since go seems to cache the toolexec output
# Cleanup: rm -f /tmp/golog
# Usage (compile all tests only): `go test -exec=true -toolexec=$PWD/tools/go-compile-verbose ./...`
# Usage (compile binary): `go build -toolexec=true -toolexec=$PWD/tools/go-compile-verbose ./...`
# Results will be in /tmp/golog, as stdout gets cached and pollutes all later runs.
START="$(date -u +%s.%N)"

# Output a message, with a timestamp matching istio log format
function log() {
  delta=$(date +%s.%N --date="$START seconds ago")
  echo -e "$(date -u '+%Y-%m-%dT%H:%M:%S.%NZ')\t${delta}s\t$*" >&2 >> /tmp/golog
}

ROOT="$(go env GOROOT)"
GPATH="$(go env GOPATH)"

$@
ls="$(basename $1)"
shift
case "$ls" in
  link)
    log "Finished ${ls} $(basename ${2})" ;;
  compile)
    f=${@: -1}
    pr="$(echo "/${f}" | sed "s#${GPATH}#GOPATH#g" | sed "s#${ROOT}#GOROOT#g")"
    log "Finished ${ls} ${pr}"
    ;;
  vet)
    # vet does not readily expose what is being vetted
    log "Finished ${ls}" ;;
  *)
    log "Finished ${ls}" ;;
esac
#echo "$@"
