#!/bin/bash

set -e

orig_dir=$(pwd)
repos=("delfin" "dinfra" "dinput" "dmeasures" "doutput" "dtab")

cd ~/delfinverse

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

  # Skip repo if there are uncommitted changes
  if ! git diff --quiet || ! git diff --cached --quiet; then
    echo "⚠️  Uncommitted changes in $repo – skipping"
    cd ..
    continue
  fi

  # Fetch all updates and branches
  git fetch --all --prune

  # Create local tracking branches for all remote branches
  for remote_branch in $(git branch -r | grep -v '\->'); do
    local_branch="${remote_branch#origin/}"
    if ! git show-ref --quiet refs/heads/"$local_branch"; then
      echo "🔄 Creating local branch: $local_branch"
      git checkout -b "$local_branch" --track "$remote_branch"
    fi
  done

  # Pull updates for all local branches
  for branch in $(git for-each-ref --format='%(refname:short)' refs/heads/); do
    git checkout "$branch"
    git pull --ff-only origin "$branch" || true
  done

  git checkout main
  cd ..
done

cd "$orig_dir"

echo "✅ Updates completed (repos with uncommitted changes were skipped)."