#!/bin/sh

set -ef

PKGSRC=${PKGSRC:-github.com/yggdrasil-network/yggdrasil-go/src/version}
PKGNAME=${PKGNAME:-$(sh contrib/semver/name.sh)}
PKGVER=${PKGVER:-$(sh contrib/semver/version.sh --bare)}

LDFLAGS="-X $PKGSRC.buildName=$PKGNAME -X $PKGSRC.buildVersion=$PKGVER"
ARGS="-v"

while getopts "uaitc:l:dro:p" option
do
  case "$option"
  in
  u) UPX=true;;
  i) IOS=true;;
  a) ANDROID=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";;
  esac
done

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

if [ $IOS ]; then
  echo "Building framework for iOS"
  gomobile bind -target ios -tags mobile -ldflags="$LDFLAGS $STRIP" -gcflags="$GCFLAGS" \
    github.com/yggdrasil-network/yggdrasil-go/src/yggdrasil \
    github.com/yggdrasil-network/yggdrasil-go/src/config \
    github.com/yggdrasil-network/yggdrasil-extras/src/mobile \
    github.com/yggdrasil-network/yggdrasil-extras/src/dummy
elif [ $ANDROID ]; then
  echo "Building aar for Android"
  gomobile bind -target android -tags mobile -ldflags="$LDFLAGS $STRIP" -gcflags="$GCFLAGS" \
    github.com/yggdrasil-network/yggdrasil-go/src/yggdrasil \
    github.com/yggdrasil-network/yggdrasil-go/src/config \
    github.com/yggdrasil-network/yggdrasil-extras/src/mobile \
    github.com/yggdrasil-network/yggdrasil-extras/src/dummy
else
  for CMD in yggdrasil yggdrasilctl ; do
    echo "Building: $CMD"
    go build $ARGS -ldflags="$LDFLAGS" -gcflags="$GCFLAGS" ./cmd/$CMD

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