#!/bin/sh
# POSIX wrapper around the platform-native `fabled-bin` that the
# postinstall script downloaded into the sibling directory.
#
# When npm installs `@fabledos/cli` globally, it creates a symlink at
# `<npm-prefix>/bin/fabled` pointing here. A naïve `dirname "$0"` would
# return the symlink's directory (`<npm-prefix>/bin`) rather than the
# wrapper's real location, and the exec would fail with "fabled-bin: No
# such file or directory."
#
# This snippet resolves symlinks (POSIX-portable; macOS BSD readlink
# lacks `-f` without coreutils, so we hand-roll the loop) and ends up
# with the wrapper's *real* directory in `DIR`. `fabled-bin` lives
# there.
#
# Per ADR-0028 follow-up; see CHANGELOG entry for v0.5.2.

set -e

SCRIPT_PATH="$0"
while [ -L "$SCRIPT_PATH" ]; do
  LINK_TARGET="$(readlink "$SCRIPT_PATH")"
  case "$LINK_TARGET" in
    /*) SCRIPT_PATH="$LINK_TARGET" ;;
    *)  SCRIPT_PATH="$(dirname "$SCRIPT_PATH")/$LINK_TARGET" ;;
  esac
done

DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
exec "$DIR/fabled-bin" "$@"
