#!/bin/bash
set -ef

PKGSRC=${PKGSRC:-github.com/RiV-chain/RiV-mesh/src/version}
PKGNAME=${PKGNAME:-$(sh contrib/semver/name.sh)}
PKGVER=${PKGVER:-$(sh contrib/semver/version.sh --bare)}
echo "Building: $PKGVER"

if [ "$LDFLAGS" ]; then
  LDFLAGS="$LDFLAGS -X $PKGSRC.buildName=$PKGNAME -X $PKGSRC.buildVersion=$PKGVER"
else
  LDFLAGS="-X $PKGSRC.buildName=$PKGNAME -X $PKGSRC.buildVersion=$PKGVER"
fi
ARGS="-v"

TARGET_PATH=$(pwd)
while getopts "utc:l:dro:psg:b:" option
do
  case "$option"
  in
  u) UPX=true;;
  t) TABLES=true;;
  c) GCFLAGS="$GCFLAGS $OPTARG";;
  l) LDFLAGS="$LDFLAGS $OPTARG";;
  d) ARGS="$ARGS -tags debug" DEBUG=true;;
  r) ARGS="$ARGS -race";;
  o) ARGS="$ARGS -o $OPTARG";;
  p) ARGS="$ARGS -buildmode=pie";;
  # statically linked executable
  s) STATIC=" -linkmode external -extldflags=-static";;
  # build target
  g) TARGET=$OPTARG;;
  # build path
  b) TARGET_PATH=$OPTARG;;
  esac
done

if [ -z $TABLES ] && [ -z $DEBUG ]; then
  LDFLAGS="$LDFLAGS -s -w"
fi

#could be static
buildbin() {
  local CMD=$(realpath $1)
  echo "Building: $CMD for $GOOS-$GOARCH"

  (cd "$TARGET_PATH" && go build $ARGS -ldflags "${LDFLAGS}${LDFLAGS2}" -gcflags "$GCFLAGS" "$CMD")

  if [ $UPX ]; then
    upx --brute "$CMD"
  fi
}

build_mesh() {
  LDFLAGS2="${STATIC}" buildbin ./cmd/mesh
}

build_meshctl() {
  LDFLAGS2="${STATIC}" buildbin ./cmd/meshctl
}

build_mesh_ui() {
  buildbin ./contrib/ui/mesh-ui
}

case $TARGET in 
  "mesh")
    build_mesh
    ;;
  "meshctl")
    build_meshctl
    ;;
  "mesh_ui")
    build_mesh_ui
    ;;
  *)
    build_mesh
    build_meshctl
    build_mesh_ui
    ;;
esac
