#!/usr/bin/env bash
set -e  # Exit on error

# --- 1. Create fresh repo and branches ---
rm -rf .git
git init

proj="proj"

# Initial commit on main
echo "Base project readme" > README.md
git add README.md
git commit -m "Initial commit on main"

# Create branches from main with unique files
for version in v1 v2 v3; do
    branch="$version"
    file="${proj}_${version}.txt"

    git checkout -b "$branch" main
    echo "This is $version" > "$file"
    git add "$file"
    git commit -m "Add $file for $branch"
done

# --- 2. List all branches and files in each ---
echo
echo "=== Branches and their files ==="
for branch in main v1 v2 v3; do
    echo "--- $branch ---"
    git ls-tree -r --name-only "$branch"
done

# --- 3. Show diff of file names between branches (portable) ---
echo
echo "=== File name differences between branches ==="
for b1 in main v1 v2 v3; do
    for b2 in main v1 v2 v3; do
        if [[ "$b1" != "$b2" ]]; then
            echo "Diff: $b1 vs $b2"
            tmp1=$(mktemp)
            tmp2=$(mktemp)
            git ls-tree -r --name-only "$b1" | sort > "$tmp1"
            git ls-tree -r --name-only "$b2" | sort > "$tmp2"
            diff "$tmp1" "$tmp2" || true
            rm -f "$tmp1" "$tmp2"
            echo
        fi
    done
done

# --- 4. Checkout v2 ---
git checkout v2
echo
echo "=== Active branch ==="
git branch --show-current
echo "Files in working directory:"
ls -1
