#!/bin/bash

# Exit bash script if any of the commands fails
set -e
# Back up the original package.json
cp package.json package.json.bak

# Remove all dependencies starting with the prefix @dyte-in
# The imported types from these dependencies will be bundled
cat package.json.bak | jq '.dependencies |= delpaths([keys[] | select(contains("@dyte-in") or contains("@dyteinternals")) | [.]])' >package.json

function restore {
  echo "Restoring package.json"
  mv package.json.bak package.json
}

# Always run the restore function on exit
trap restore EXIT

npx tsup src/index.ts --external @dytesdk/mediasoup-client --dts-resolve --dts-only --format esm

npx tsup src/e2ee/EncryptionManager.ts --dts-resolve --dts-only --format esm

npx tsup src/mock/DyteClientMock.ts --dts-resolve --dts-only --format esm

OS="$(uname)"
SED_CMD=""

if [[ "$OS" == "Darwin" ]]; then
  # macOS (BSD sed requires backup extension or '')
  SED_CMD="sed -i '' '/#private;/d'"
else
  # Linux (GNU sed)
  SED_CMD="sed -i '/#private;/d'"
fi

echo $SED_CMD

# Find and process all .d.ts files
find dist/ -name '*.d.ts' -exec bash -c "$SED_CMD \"{}\"" \;
