#!/usr/bin/env bash
set -euo pipefail

studio="$(cd "$(dirname "$0")/.." && pwd)"
if [[ "${ELE_BIN:-}" != /* || ! -x "${ELE_BIN:-}" ]]; then
  echo 'set ELE_BIN to the absolute path of an installed ele executable' >&2
  exit 2
fi
if [[ "${PROJECT:-}" != /* || ! -d "${PROJECT:-}" ]]; then
  echo 'set PROJECT to the absolute path of an existing ELE project' >&2
  exit 2
fi

action="${1:-}"
case "$action" in
  attach)
    id="${2:-}"
    [[ "$#" -eq 2 && "$id" =~ ^[a-z][a-z0-9._-]*$ && -f "$studio/extensions/$id/manifest.json" ]] || {
      echo 'usage: bin/dev attach EXTENSION_ID' >&2
      exit 2
    }
    exec "$ELE_BIN" --root "$PROJECT" extension dev attach "$studio/extensions/$id"
    ;;
  status)
    [[ "$#" -eq 1 ]] || { echo 'usage: bin/dev status' >&2; exit 2; }
    exec "$ELE_BIN" --root "$PROJECT" extension dev status
    ;;
  detach)
    id="${2:-}"
    [[ "$#" -eq 2 && "$id" =~ ^[a-z][a-z0-9._-]*$ ]] || {
      echo 'usage: bin/dev detach EXTENSION_ID' >&2
      exit 2
    }
    exec "$ELE_BIN" --root "$PROJECT" extension dev detach "$id"
    ;;
  *)
    echo 'usage: bin/dev attach EXTENSION_ID | status | detach EXTENSION_ID' >&2
    exit 2
    ;;
esac
