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

repo_root=$1
ref=$2
target=$3
snapshot_paths=()

for path in website/docs website/component website/base website/shell website/zh-CN; do
  rm -rf "$target/${path#website/}"
  if git -C "$repo_root" cat-file -e "$ref:$path" 2>/dev/null; then
    snapshot_paths+=("$path")
  fi
done

if ((${#snapshot_paths[@]} > 0)); then
  git -C "$repo_root" archive "$ref" "${snapshot_paths[@]}" \
    | tar -x --strip-components=1 -C "$target"
fi

# gpui-shell ships as a binary attached to a release, and a release's binary
# can be rebuilt after the tag (`release-shell.yml` records the commit it built
# from as `shell-<tag>`). Its pages then describe that binary, not the tag.
shell_ref="shell-$ref"
if git -C "$repo_root" rev-parse -q --verify "refs/tags/$shell_ref" >/dev/null; then
  shell_paths=()
  for path in website/shell website/zh-CN/shell; do
    rm -rf "$target/${path#website/}"
    if git -C "$repo_root" cat-file -e "$shell_ref:$path" 2>/dev/null; then
      shell_paths+=("$path")
    fi
  done
  if ((${#shell_paths[@]} > 0)); then
    git -C "$repo_root" archive "$shell_ref" "${shell_paths[@]}" \
      | tar -x --strip-components=1 -C "$target"
  fi
fi

if git -C "$repo_root" cat-file -e "$ref:website/src/components/HomeApp.vue" 2>/dev/null; then
  rm -f "$target/src/components/HomeApp.vue"
  git -C "$repo_root" archive "$ref" website/src/components/HomeApp.vue \
    | tar -x --strip-components=3 -C "$target/src/components"
fi

bun "$(dirname "$0")/../website/src/lib/normalize-doc-versions.js" "$target"
