#!/usr/bin/env bash
# Usage: script/build [-o output] [test]
#
# Sets up GOPATH and compiles hub. With `test`, runs tests instead.

set -e

windows=
[[ $OS == Windows* ]] && windows=1

setup_gopath() {
  TMPDIR="${LOCALAPPDATA:-$TMPDIR}"
  TMP_GOPATH="${TMPDIR:-/tmp}/go"
  TMP_SELF="${TMP_GOPATH}/src/github.com/github/hub"

  if [ -n "$windows" ]; then
    export GOPATH="${TMP_GOPATH//\//\\}"
  else
    export GOPATH="$TMP_GOPATH"
  fi

  export GO15VENDOREXPERIMENT=1

  mkdir -p "${TMP_SELF%/*}"
  ln -snf "$PWD" "$TMP_SELF" 2>/dev/null || {
    rm -rf "$TMP_SELF"
    mkdir "$TMP_SELF"
    cp -R "$PWD"/* "${TMP_SELF}/"
  }
}

find_source_files() {
  find . -maxdepth 2 -name '*.go' '!' -name '*_test.go' "$@"
}

find_packages() {
  find_source_files | cut -d/ -f2 | sort -u | grep -v '.go$' | sed 's!^!github.com/github/hub/!'
}

count_changed_files() {
  printf %d $(find_source_files -newer "$1" | wc -l)
}

up_to_date() {
  [ -e "$1" ] && [ "$(count_changed_files "$1")" -eq 0 ]
}

build_hub() {
  setup_gopath
  [ -n "$1" ] && (up_to_date "$1" || go build -ldflags "-X github.com/github/hub/version.Version=`./script/version`" -o "$1")
}

test_hub() {
  setup_gopath
  find_packages | xargs go test
}

case "$1" in
"" )
  build_hub hub${windows:+.exe}
  ;;
-o )
  shift
  build_hub $1
  ;;
test )
  test_hub
  ;;
files )
  find_source_files
  ;;
-h | --help )
  sed -ne '/^#/!q;s/.\{1,2\}//;1d;p' < "$0"
  exit
  ;;
* )
  "$0" --help >&2
  exit 1
esac
