#!/bin/bash
[% c("var/set_default_env") -%]
[% pc('go', 'var/setup', { go_tarfile => c('input_files_by_name/go') }) %]
[% pc(c('var/compiler'), 'var/setup', { compiler_tarfile => c('input_files_by_name/' _ c('var/compiler')) }) %]
[% IF c("var/linux") %]
  tar -C /var/tmp/dist -xf $rootdir/[% c('input_files_by_name/binutils') %]
  export PATH="/var/tmp/dist/binutils/bin:$PATH"
  # The go-webrtc package sets _GLIBCXX_USE_CXX11_ABI=0 for compatibility with
  # the prebuilt libwebrtc-magic.a libraries. Since we build our own
  # libwebrtc-magic.a with the C++11 ABI, we have to undo that setting here,
  # using CGO_CXXFLAGS.
  export CGO_CXXFLAGS="-D_GLIBCXX_USE_CXX11_ABI=1"
[% END -%]
distdir=/var/tmp/dist/[% project %]
[% c("var/set_PTDIR_DOCSDIR") -%]
mkdir -p $PTDIR $DOCSDIR
[% IF c("var/osx") %]
  export CGO_ENABLED=1
  export CGO_CFLAGS="[% c("var/FLAGS") %] -mmacosx-version-min=10.7"
  export CGO_CXXFLAGS="[% c("var/FLAGS") %] -stdlib=libc++ -mmacosx-version-min=10.7"
  export CGO_LDFLAGS="[% c("var/FLAGS") %] -stdlib=libc++ -mmacosx-version-min=10.7"
  export CC="$clangdir/bin/clang"
  export CXX="$clangdir/bin/clang++"
[% END %]

tar -C /var/tmp/dist -xf [% c('input_files_by_name/go-webrtc') %]
tar -C /var/tmp/dist -xf [% c('input_files_by_name/uniuri') %]
tar -C /var/tmp/dist -xf [% c('input_files_by_name/goptlib') %]

mkdir -p /var/tmp/build
tar -C /var/tmp/build -xf [% project %]-[% c('version') %].tar.gz
cd /var/tmp/build/[% project %]-[% c('version') %]

cd client
[% IF c("var/osx") -%]
  # Without faketime, snowflake-client would contain the timestamp of the
  # temporary client.a file created during "go build".
  # The -tmpdir flag overrides what would otherwise be a randomly generated
  # path, /tmp/go-link-RANDOMNUM/go.o.
  mkdir -p /var/tmp/go-link.tmpdir
  [% c("var/faketime") %] go build -ldflags '-s -tmpdir /var/tmp/go-link.tmpdir'
[% ELSE -%]
  go build -ldflags '-s'
[% END -%]
cp -a client[% IF c("var/windows") %].exe[% END %] $PTDIR/snowflake-client[% IF c("var/windows") %].exe[% END %]

cd ..
cp -a README.md LICENSE $DOCSDIR

cd $distdir
[% c('tar', {
        tar_src => [ '.' ],
        tar_args => '-czf ' _ dest_dir _ '/' _ c('filename'),
    }) %]
