#!/bin/bash

set -e

# Speichere aktuelles Arbeitsverzeichnis
orig_dir=$(pwd)

# Repositories in delfinverse
repos=("delfin" "dinfra" "dinput" "dmeasures" "doutput" "dtab")

cd ~/delfinverse

for repo in "${repos[@]}"; do
  echo "========= SETUP $repo ========="
  cd "$repo"

  # Git-Fetch durchführen, um aktuelle Remote-Branches zu haben
  git fetch --all

  # Lokale main-Branch löschen und neu von origin/main auschecken
  git checkout --detach
  git branch -D main
  git checkout -b main origin/main

  # Alle lokalen Branches durchgehen
  for local_branch in $(git for-each-ref --format='%(refname:short)' refs/heads/); do
    if [ "$local_branch" = "main" ]; then
      continue
    fi

    if git show-ref --verify --quiet "refs/remotes/origin/$local_branch"; then
      echo "🗑️  Deleting local branch $local_branch (exists on origin)"
      git branch -D "$local_branch"
    else
      echo "💾 Keeping local-only branch $local_branch"
    fi
  done

  # Remote-Branches als lokale Branches anlegen mit Tracking
  for remote_branch in $(git branch -r | grep -v '\->'); do
    local_branch="${remote_branch#origin/}"
    if [ "$local_branch" = "main" ]; then
      continue
    fi

    echo "🌱 Creating and tracking $local_branch from $remote_branch"
    git branch --track "$local_branch" "$remote_branch" 2>/dev/null || true
  done

  git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
  git fetch --all
  git config --global checkout.defaultRemote origin

  cd ..
done

# Zurück zum ursprünglichen Verzeichnis
cd "$orig_dir"

echo "✅ Setup abgeschlossen für alle Repositories."