#!/usr/bin/env bash
set -x


SOURCE_PATH=$1
BUILD_PATH=$2
COMPONENT_SLUG=$3
GO_RELEASE_PACKAGE_NAME=$4
PROJECT_VERSION=$5
PROJECT_BUILD_DATE=$6
platforms=$(go tool dist list)

included_os=("linux" "windows")

# define a list of excluded architectures
included_arch=("amd64" "arm64")

cd $SOURCE_PATH || exit 1

# Run and build loop through all platforms (except excluded ones)
for platform in $platforms; do

  # GOOS und GOARCH Variablen setzen
  export GOOS=$(echo $platform | cut -d'/' -f1)
  export GOARCH=$(echo $platform | cut -d'/' -f2)

  if [[ ! "${included_os[@]}" =~ "$GOOS" ]]; then
    echo "Skipping excluded platform: $GOOS"
    continue
  fi

  if [[ ! "${included_arch[@]}" =~ "$GOARCH" ]]; then
    echo "Skipping excluded architecture: $GOARCH"
    continue
  fi

  echo "============================================"
  echo "Building for $GOOS/$GOARCH"

  output_name=$BUILD_PATH$COMPONENT_SLUG-$GOOS-$GOARCH
  if [ $GOOS = "windows" ]; then
    output_name+='.exe'
  fi

  env GOFLAGS= GOWORK=off GO111MODULE=on GOOS=$GOOS GOARCH=$GOARCH go build -ldflags "-X $GO_RELEASE_PACKAGE_NAME.version=$PROJECT_VERSION -X $GO_RELEASE_PACKAGE_NAME.build=$PROJECT_BUILD_DATE" -o $output_name
  if [ $? -ne 0 ]; then
    echo "An error has occurred! $output_name build failed."
    echo "============================================"
  fi
done

cd - || exit 1