#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
DXCLI_DIR="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
PROJECT_ROOT="$(cd -- "${DXCLI_DIR}/.." && pwd)"
VERSION="$(python3 - "${DXCLI_DIR}" <<'PY'
import importlib.util
import pathlib
import sys

metadata_path = pathlib.Path(sys.argv[1]) / "dxcli_metadata.py"
spec = importlib.util.spec_from_file_location("dxcli_portable_metadata", metadata_path)
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(module)
print(module.DXCLI_VERSION)
PY
)"
DIST_DIR="${DXCLI_DIR}"
ARCHIVE_NAME="dxcli-portable-${VERSION}.tar.gz"

mkdir -p "${DIST_DIR}"
rm -f "${DIST_DIR}/${ARCHIVE_NAME}" "${DIST_DIR}/dxcli-portable-latest.tar.gz"
TMP_DIR="$(mktemp -d)"
cleanup() {
  rm -rf "${TMP_DIR}"
}
trap cleanup EXIT

tar \
  --exclude='__pycache__' \
  --exclude='*.pyc' \
  --exclude='*.tar.gz' \
  --exclude='dxcli-portable/scripts/install_dxcli_portable_online.sh' \
  --exclude='test_*.py' \
  --exclude='.pytest_cache' \
  --exclude='.DS_Store' \
  -czf "${TMP_DIR}/${ARCHIVE_NAME}" \
  -C "${PROJECT_ROOT}" \
  dxcli-portable

mv "${TMP_DIR}/${ARCHIVE_NAME}" "${DIST_DIR}/${ARCHIVE_NAME}"
cp "${DIST_DIR}/${ARCHIVE_NAME}" "${DIST_DIR}/dxcli-portable-latest.tar.gz"
echo "${DIST_DIR}/${ARCHIVE_NAME}"
