#!/bin/bash

# omarchy:summary=Run a command while holding the Omarchy update lock
# omarchy:args=<held|run> [command] [args...]
# omarchy:hidden=true

set -e

lock_dir="${XDG_RUNTIME_DIR:-/tmp}"
lock_path="$lock_dir/omarchy-update.lock"

lock_is_held() {
  local lock_fd_path=""

  [[ -n ${OMARCHY_UPDATE_LOCK_FD:-} && -e /proc/$$/fd/$OMARCHY_UPDATE_LOCK_FD ]] || return 1

  lock_fd_path=$(readlink -f "/proc/$$/fd/$OMARCHY_UPDATE_LOCK_FD" 2>/dev/null || true)
  [[ $lock_fd_path == "$(readlink -m "$lock_path")" ]] &&
    flock -n "$OMARCHY_UPDATE_LOCK_FD"
}

case "${1:-}" in
  held)
    lock_is_held
    ;;
  run)
    shift
    if (( $# == 0 )); then
      echo "Usage: omarchy-update-lock run <command> [args...]" >&2
      exit 2
    fi

    mkdir -p "$lock_dir" 2>/dev/null || true
    exec {OMARCHY_UPDATE_LOCK_FD}>"$lock_path"
    if ! flock -n "$OMARCHY_UPDATE_LOCK_FD"; then
      echo "An Omarchy update is already running."
      exit 1
    fi

    export OMARCHY_UPDATE_LOCK_FD
    exec "$@"
    ;;
  *)
    echo "Usage: omarchy-update-lock <held|run> [command] [args...]" >&2
    exit 2
    ;;
esac
