#!/usr/bin/env bash
# Push a clean release snapshot to the public GitHub repo.
#
# Usage:
#   scripts/push-public.sh v0.2.0    # release a specific tag
#   scripts/push-public.sh           # snapshot of HEAD (for testing)
#
# Files marked 'export-ignore' in .gitattributes are excluded automatically.
# Requires the 'public' git remote to be configured:
#   git remote add public git@github.com:MrErin/unfamiliar.git

set -euo pipefail

REF="${1:-HEAD}"
PUBLIC_REMOTE="${PUBLIC_REMOTE:-public}"
BRANCH="main"

# Capture public remote URL now, before we change directories
PUBLIC_URL=$(git remote get-url "$PUBLIC_REMOTE")

# Resolve a tag name if the ref is an exact tag
if TAG=$(git describe --exact-match "$REF" 2>/dev/null); then
    COMMIT_MSG="Release $TAG"
else
    TAG=""
    SHORT_SHA=$(git rev-parse --short "$REF")
    COMMIT_MSG="Snapshot $SHORT_SHA"
fi

echo "→ Preparing: $COMMIT_MSG"

# Create a temp directory; clean it up on exit regardless of success/failure
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

# git archive respects export-ignore entries in .gitattributes
git archive "$REF" | tar -x -C "$TMPDIR"

cd "$TMPDIR"
git init -b "$BRANCH"
git add .
git commit -m "$COMMIT_MSG"

# Tag the commit if we have a version tag
if [ -n "$TAG" ]; then
    git tag "$TAG"
fi

git remote add public "$PUBLIC_URL"
git push public "$BRANCH" --force

if [ -n "$TAG" ]; then
    git push public "$TAG"
fi

echo "✓ Published $COMMIT_MSG to public repo"