#!/bin/sh
set -eu

usage() {
  cat <<'EOF'
Download VS Code extension VSIX files for multiple platforms.

Usage:
  ./download-vsix.sh <publisher.extension> <version> [output_dir]

Examples:
  ./download-vsix.sh Continue.continue 1.2.22
  ./download-vsix.sh ms-python.python 2024.17.2024100401 ./out

Notes:
  - Downloads platform-specific VSIX packages using the VS Code Marketplace public gallery API.
  - Some extensions do not publish builds for all platforms; those downloads will be skipped.
EOF
}

if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
  usage
  exit 0
fi

if [ "$#" -lt 2 ] || [ "$#" -gt 3 ]; then
  usage >&2
  exit 2
fi

item_name="$1"
version="$2"
base_out_dir="${3:-./vsix}"

case "$item_name" in
  *.*) : ;;
  *)
  echo "error: itemName must be in the form publisher.extension (got: $item_name)" >&2
  exit 2
  ;;
esac

publisher=$(printf '%s' "$item_name" | awk -F. '{print $1}')
extension=$(printf '%s' "$item_name" | awk -F. '{print $2}')

marketplace_base="https://marketplace.visualstudio.com/_apis/public/gallery"
ext_base_url="$marketplace_base/publishers/$publisher/vsextensions/$extension/$version/vspackage"

target_platforms="
win32-x64
win32-ia32
win32-arm64
linux-x64
linux-arm64
linux-armhf
alpine-x64
alpine-arm64
darwin-x64
darwin-arm64
"

download_dir="$base_out_dir/$item_name/$version"
mkdir -p "$download_dir"

have_curl=0
have_wget=0
if command -v curl >/dev/null 2>&1; then
  have_curl=1
fi
if command -v wget >/dev/null 2>&1; then
  have_wget=1
fi
if [ "$have_curl" -eq 0 ] && [ "$have_wget" -eq 0 ]; then
  echo "error: need curl or wget installed" >&2
  exit 127
fi

download() {
  url="$1"
  out="$2"
  tmp="$out.part"

  if [ -f "$out" ]; then
    echo "exists: $out"
    return 0
  fi

  rm -f "$tmp"

  if [ "$have_curl" -eq 1 ]; then
    # -f: fail on HTTP errors, -L: follow redirects, --retry: transient errors
    if curl -fL --retry 3 --retry-delay 1 --connect-timeout 15 --max-time 600 -o "$tmp" "$url" >/dev/null 2>&1; then
      mv -f "$tmp" "$out"
      echo "ok: $out"
      return 0
    fi
  else
    if wget -q -O "$tmp" "$url"; then
      mv -f "$tmp" "$out"
      echo "ok: $out"
      return 0
    fi
  fi

  rm -f "$tmp"
  return 1
}

fail_count=0
ok_count=0

for tp in $target_platforms; do
  url="$ext_base_url?targetPlatform=$tp"
  out="$download_dir/$item_name-$version-$tp.vsix"

  if download "$url" "$out"; then
    ok_count=$((ok_count + 1))
  else
    echo "skip: $tp (not available or download failed)"
    fail_count=$((fail_count + 1))
  fi
done

# Try universal package (no targetPlatform) as well.
universal_out="$download_dir/$item_name-$version-universal.vsix"
if download "$ext_base_url" "$universal_out"; then
  ok_count=$((ok_count + 1))
else
  echo "skip: universal (not available or download failed)"
fi

echo
echo "done: ok=$ok_count failed_or_skipped=$fail_count dir=$download_dir"

