#!/bin/sh
set -eu

build_script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
. "$build_script_dir/account-gateway-sources.sh"

usage() {
  echo "usage: $0 <service> <repo> <main> <arch> <output>" >&2
  exit 2
}

[ "$#" -eq 5 ] || usage

service=$1
repo=$2
main_path=$3
arch=$4
output=$5

repo=$(cd "$repo" && pwd)
output_dir=$(dirname "$output")
mkdir -p "$output_dir"
output_dir=$(cd "$output_dir" && pwd)
output=$output_dir/$(basename "$output")
cache_root=${CP9_PREMIUM_BUILD_CACHE_DIR:-$(dirname "$output_dir")/cache}
mkdir -p "$cache_root"
cache_root=$(cd "$cache_root" && pwd)
GOCACHE=${CP9_PREMIUM_GOCACHE:-$cache_root/go-build}
mkdir -p "$GOCACHE"
GOPRIVATE=${GOPRIVATE:-github.com/tidbcloud/*}
GONOSUMDB=${GONOSUMDB:-github.com/tidbcloud/*}
export GOPRIVATE GONOSUMDB GOCACHE
goflags=${GOFLAGS:-}
case " $goflags " in
  *" -buildvcs="*) ;;
  *)
    if [ -n "$goflags" ]; then
      goflags="$goflags -buildvcs=false"
    else
      goflags="-buildvcs=false"
    fi
    ;;
esac

main_dir=$(dirname "$main_path")
build_root=$repo
if [ "$main_dir" != "." ]; then
  current=$repo/$main_dir
  while [ "$current" != "$repo" ] && [ "$current" != "/" ]; do
    if [ -f "$current/go.mod" ]; then
      build_root=$current
      break
    fi
    current=$(dirname "$current")
  done
fi
if [ ! -f "$build_root/go.mod" ]; then
  build_root=$repo
fi

rel_pkg=.
case "$main_path" in
  */*) rel_pkg=./$(dirname "$main_path") ;;
esac
case "$build_root" in
  "$repo")
    ;;
  "$repo"/*)
    rel_root=${build_root#"$repo"/}
    rel_pkg=./$(dirname "$main_path")
    rel_pkg=${rel_pkg#./$rel_root/}
    rel_pkg=./$rel_pkg
    ;;
esac

case "$service" in
  account-provider|account-acl|account-central)
    generate_account_gateway_sources \
      "$repo" "$cache_root/account-tools" "[cp9 persona live-update] $service"
    ;;
esac

tmp=$output.tmp.$$
rm -f "$tmp"
printf '%s\n' "[cp9 persona live-update] $service: go build $rel_pkg"
if [ -f "$build_root/go.mod" ]; then
  GOFLAGS="$goflags" \
    CGO_ENABLED=0 GOOS=linux GOARCH="$arch" \
    go -C "$build_root" build -o "$tmp" "$rel_pkg"
else
  GO111MODULE=off CGO_ENABLED=0 GOOS=linux GOARCH="$arch" \
    go -C "$build_root" build -o "$tmp" "$rel_pkg"
fi
chmod 755 "$tmp"
mv "$tmp" "$output"
