#!/bin/bash

# omarchy:summary=Run pending Omarchy migrations.
# omarchy:args=[--pending]

set -euo pipefail

mode="run"

usage() {
  echo "Usage: omarchy-migrate [--pending]"
}

while (($#)); do
  case "$1" in
    --pending|--check)
      mode="pending"
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      exit 1
      ;;
  esac
done

OMARCHY_PATH="${OMARCHY_PATH:-/usr/share/omarchy}"
STATE_DIR="${OMARCHY_MIGRATION_STATE:-$HOME/.local/state/omarchy/migrations}"
MIGRATIONS_DIR="$OMARCHY_PATH/migrations"

allowed() {
  awk -v n="$1" '!/^#/ && $1 == n { found = 1 } END { exit !found }' /usr/share/armbian-hyprland-shell/migrations.allow 2>/dev/null
}

migration_entries() {
  [[ -d $MIGRATIONS_DIR ]] || return 0

  local file filename

  for file in "$MIGRATIONS_DIR"/*.sh; do
    [[ -f $file ]] || continue
    filename=${file##*/}
    printf '%s\t%s\t%s\n' "$filename" "$file" "$STATE_DIR/$filename"
  done
}

pending_migrations() {
  local name file marker

  while IFS=$'\t' read -r name file marker; do
    [[ -n $name ]] || continue
    if [[ ! -f $marker ]] && allowed "$name"; then
      printf '%s\n' "$name"
    fi
  done < <(migration_entries)
}

if [[ $mode == "pending" ]]; then
  pending_output=$(pending_migrations)
  if [[ -n $pending_output ]]; then
    printf '%s\n' "$pending_output"
    exit 0
  else
    exit 1
  fi
fi

wait_for_pacman_transaction() {
  local lock_file=/var/lib/pacman/db.lck

  [[ -e $lock_file ]] || return 0
  echo "$(omarchy-i18n update.migrationsWaiting)"

  for _ in {1..900}; do
    [[ -e $lock_file ]] || return 0
    sleep 1
  done

  echo "$(omarchy-i18n update.migrationsDeferred)"
  exit 0
}

wait_for_pacman_transaction

mkdir -p "$STATE_DIR"
[[ -d $MIGRATIONS_DIR ]] || exit 0

deferred=0
while IFS=$'\t' read -r name file marker <&3; do
  [[ -n $name ]] || continue

  if [[ ! -f $marker ]] && ! allowed "$name"; then
    mkdir -p "$(dirname "$marker")"
    touch "$marker"
  elif [[ ! -f $marker ]]; then
    echo -e "\e[32m\n$(omarchy-i18n update.migration "${name%.sh}")\e[0m"
    status=0
    OMARCHY_PATH="$OMARCHY_PATH" bash -euo pipefail "$file" 3<&- || status=$?

    # 75 (EX_TEMPFAIL) means the migration is waiting on a package that has not
    # landed yet, such as a dev checkout ahead of its settings package. It stays
    # pending and holds back the rest of the queue, but the update goes on.
    if (( status == 75 )); then
      echo "$(omarchy-i18n update.migrationDeferred "${name%.sh}")"
      deferred=1
      break
    elif (( status != 0 )); then
      exit $status
    fi

    mkdir -p "$(dirname "$marker")"
    touch "$marker"
  fi
done 3< <(migration_entries)

# Clear a login-time notification the user left sitting there and then resolved
# by running migrations some other way. The substring matches both the current
# and legacy notification titles. A deferred migration is still pending, so its
# reminder stays.
if (( ! deferred )); then
  omarchy-notification-dismiss "Omarchy Migrations" >/dev/null 2>&1 || true
fi
