#!/bin/bash
[% c("var/set_default_env") -%]
distdir=/var/tmp/dist/[% project %]
mkdir -p /var/tmp/dist

tar -C /var/tmp/dist -xf $rootdir/[% c('input_files_by_name/go-bootstrap') %]
export GOROOT_BOOTSTRAP="/var/tmp/dist/go-bootstrap"

cd $rootdir
[% IF ! c("var/linux") %]
  [% pc(c('var/compiler'), 'var/setup', { compiler_tarfile => c('input_files_by_name/' _ c('var/compiler')) }) %]
  # http://golang.org/doc/install/source#environment
  export GOOS=[% c("var/GOOS") %]
  export GOARCH=[% c("var/GOARCH") %]
[% END %]

# Building go
# http://golang.org/doc/install/source#environment
tar -C /var/tmp/dist -xf $rootdir/[% c('input_files_by_name/go') %]
export GOROOT="$distdir"
cd /var/tmp/dist/go/src
[% IF c("var/linux") -%]
  ./make.bash
[% ELSIF c("var/macos") -%]
  rm -Rf $clangdir/helpers
  CGO_ENABLED=1 CC_FOR_TARGET="$clangdir/bin/clang [% c('var/FLAGS') %]" \
    CC= CFLAGS= LDFLAGS= ./make.bash
[% ELSIF c("var/windows") -%]
  CC_FOR_TARGET='[% c("arch") %]-w64-mingw32-cc [% c("var/CFLAGS") %] [% c("var/LDFLAGS") %]' \
    CGO_ENABLED=1 CC= CFLAGS= LDFLAGS= ./make.bash
[% ELSIF c("var/android") -%]
  CGO_ENABLED=1 CC_FOR_TARGET=[% c("var/CC") %] CC= CFLAGS= LDFLAGS= ./make.bash
[% END -%]

# This directory is non-reproducible and doesn't exist in official Go releases,
# so remove it to preserve reproducibility of the output.
rm -rf /var/tmp/dist/go/pkg/obj/go-build/

# Disable go autoupdates (tor-browser-build#41345)
# See https://go.dev/doc/toolchain
sed -i -e 's/^GOTOOLCHAIN=.*/GOTOOLCHAIN=local/' /var/tmp/dist/go/go.env

cd /var/tmp/dist
[% c('tar', {
        tar_src => [ project ],
        tar_args => '-caf ' _ dest_dir _ '/' _ c('filename'),
    }) %]
