#!/bin/bash

# archypr:summary=Switch Omarchy branches and update from the selected branch
# archypr:args=<branch>

set -e

if (($# == 0)); then
  echo "Usage: archypr-update-branch [master|dev]"
  exit 1
fi

branch="$1"

# Snapshot before switching branch
archypr-napshot create || (( $? == 127 ))

if ! git -C "$ARCHYPR_PATH" diff --quiet || ! git -C "$ARCHYPR_PATH" diff --cached --quiet; then
  stashed=true
  git -C "$ARCHYPR_PATH" stash push -u -m "Autostash before switching to $branch"
else
  stashed=false
fi

# Switch branches
git -C "$ARCHYPR_PATH" switch "$branch"

# Reapply stash if we made one
if [[ $stashed == "true" ]]; then
  if ! git -C "$ARCHYPR_PATH" stash pop; then
    echo "⚠️ Conflicts when applying stash — stash kept"
  fi
fi

# Update the system from the new branch
archypr-pdate-perform
