#!/bin/bash

VERSION=$1

rm -rf teleport-*.tar.?z go-modules-teleport* cargo-teleport* cargo-ironrdp* cargo-rdpclient* yarn-teleport*

echo "Downloading teleport-$VERSION..."

# git clone https://github.com/gravitational/teleport.git teleport-$VERSION

wget "https://github.com/gravitational/teleport/archive/v$VERSION/teleport-$VERSION.tar.gz"

tar xf teleport-$VERSION.tar.gz
mkdir -p go-modules-teleport-$VERSION

# cd teleport-$VERSION
#   git checkout v$VERSION
#   git submodule init
#   git submodule update webassets
# cd ..

# tar --exclude-vcs -cf teleport-$VERSION.tar teleport-$VERSION

cd teleport-$VERSION
  if ! [ -f /usr/bin/cargo-vendor-filterer ]; then
    echo "WARNING: Creating unfiltered vendor libs tarball!"
    cargo vendor
  else
    cargo vendor-filterer --platform="x86_64-unknown-linux-gnu" --platform="i686-unknown-linux-gnu"
  fi

  mv vendor ../cargo-teleport-$VERSION

  yarn install --ignore-scripts --cache-folder .yarn
  mv .yarn ../yarn-teleport-$VERSION

  export GOPATH=$(realpath ../go-modules-teleport-$VERSION)
  go mod download

  cd build.assets/tooling
    go mod download
  cd ../..

  cd web/packages/teleport/src/ironrdp
    if ! [ -f /usr/bin/cargo-vendor-filterer ]; then
      echo "WARNING: Creating unfiltered vendor libs tarball!"
      cargo vendor
    else
      cargo vendor-filterer --platform="x86_64-unknown-linux-gnu" --platform="i686-unknown-linux-gnu"
    fi

    mv vendor ../../../../../../cargo-ironrdp-$VERSION
  cd ../../../../../

  cd lib/srv/desktop/rdp/rdpclient
    if ! [ -f /usr/bin/cargo-vendor-filterer ]; then
      echo "WARNING: Creating unfiltered vendor libs tarball!"
      cargo vendor
    else
      cargo vendor-filterer --platform="x86_64-unknown-linux-gnu" --platform="i686-unknown-linux-gnu"
    fi

    mv vendor ../../../../../../cargo-rdpclient-$VERSION
  cd ../../../../../
cd ..

cd go-modules-teleport-$VERSION/pkg/mod/cache/
  mv download go-modules-teleport-$VERSION
  tar cf ../../../../go-modules-teleport-$VERSION.tar go-modules-teleport-$VERSION
cd ../../../../

tar cf cargo-teleport-$VERSION.tar cargo-teleport-$VERSION
tar cf cargo-ironrdp-$VERSION.tar cargo-ironrdp-$VERSION
tar cf cargo-rdpclient-$VERSION.tar cargo-rdpclient-$VERSION
tar cf yarn-teleport-$VERSION.tar yarn-teleport-$VERSION

plzip -9 cargo-teleport-$VERSION.tar
plzip -9 cargo-ironrdp-$VERSION.tar
plzip -9 cargo-rdpclient-$VERSION.tar
plzip -9 go-modules-teleport-$VERSION.tar
plzip -9 yarn-teleport-$VERSION.tar

gunzip teleport-$VERSION.tar.gz
plzip -9 teleport-$VERSION.tar

rm -rf teleport-$VERSION
rm -rf cargo-teleport-$VERSION
rm -rf cargo-ironrdp-$VERSION
rm -rf cargo-rdpclient-$VERSION
rm -rf go-modules-teleport-$VERSION
rm -rf yarn-teleport-$VERSION
