#!/bin/bash

VERSION=$1

rm -rf zed-*.tar.?z cargo-zed* cargo-config-zed* webrtc-*.tar.?z

echo "Downloading zed-$VERSION..."

wget --content-disposition "https://github.com/zed-industries/zed/archive/refs/tags/v$VERSION.tar.gz" || exit 1

tar xf zed-$VERSION.tar.gz || exit 1

cd zed-$VERSION
  # cargo prints the source config these vendored crates need (git
  # dependencies included) on stdout. Keep it for the SlackBuild.
  if ! [ -f /usr/bin/cargo-vendor-filterer ]; then
    echo "WARNING: Creating unfiltered vendor libs tarball!"
    cargo vendor vendor > ../cargo-config-zed-$VERSION.toml || exit 1
  else
    cargo vendor-filterer --platform="x86_64-unknown-linux-gnu" --platform="i686-unknown-linux-gnu" --all-features vendor > ../cargo-config-zed-$VERSION.toml || exit 1
  fi

  mv vendor ../cargo-zed-$VERSION

  # webrtc-sys downloads a prebuilt libwebrtc during the build unless
  # LK_CUSTOM_WEBRTC points to one. Fetch it here for an offline build.
  WEBRTC_TAG=$(grep -ohP 'WEBRTC_TAG: &str = "\K[^"]+' ../cargo-zed-$VERSION/webrtc-sys-build*/src/lib.rs | head -n 1)
cd ..

if [ -z "$WEBRTC_TAG" ]; then
  echo "ERROR: Could not determine the WebRTC tag!"
  exit 1
fi

wget "https://github.com/zed-industries/livekit-rust-sdks/releases/download/$WEBRTC_TAG/webrtc-linux-x64-release.zip" || exit 1
mkdir $WEBRTC_TAG
unzip -q webrtc-linux-x64-release.zip -d $WEBRTC_TAG || exit 1
tar cf $WEBRTC_TAG.tar $WEBRTC_TAG

gunzip zed-$VERSION.tar.gz
tar cf cargo-zed-$VERSION.tar cargo-zed-$VERSION

plzip -9 zed-$VERSION.tar
plzip -9 cargo-zed-$VERSION.tar
plzip -9 $WEBRTC_TAG.tar

rm -rf zed-$VERSION
rm -rf cargo-zed-$VERSION
rm -rf $WEBRTC_TAG
rm -f webrtc-linux-x64-release.zip
