#!/bin/bash

cd ~/.local/share/omarchy

if [[ $1 == "all" ]]; then
  # Run all migrations since the root commit
  migration_starting_point=$(git log --max-parents=0 --first-parent --format="%H")
else
  # Remember the commit we're at before upgrading in order to only run new migrations
  migration_starting_point=$(git log -1 --format=%H)
fi

# Get the latest while trying to preserve any modifications
git pull --autostash
git diff --check || git reset --merge

# Run any pending migrations
for file in $(git diff --name-only --diff-filter=A $migration_starting_point.. migrations/*.sh); do
  filename=$(basename "$file")
  migrate_at="${filename%.sh}"

  echo -e "\e[32m\nRunning migration ($migrate_at)\e[0m"
  source $file
done

# Update system packages
echo -e "\e[32m\nUpdate system packages\e[0m"
yay -Syu --noconfirm

# Back to where we came from
cd - >/dev/null
