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

APP_DIR="${APP_DIR:-release/AnotherEditor.app}"
INSTALL_DIR="${INSTALL_DIR:-${HOME}/Applications}"

if [[ ! -d "${APP_DIR}" ]]; then
  echo "App bundle not found: ${APP_DIR}" >&2
  echo "Run 'make macos-app-bundle' first." >&2
  exit 1
fi

mkdir -p "${INSTALL_DIR}"
rm -rf "${INSTALL_DIR}/AnotherEditor.app"
cp -R "${APP_DIR}" "${INSTALL_DIR}/AnotherEditor.app"

LSREGISTER="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
if [[ -x "${LSREGISTER}" ]]; then
  "${LSREGISTER}" -f "${INSTALL_DIR}/AnotherEditor.app" >/dev/null 2>&1 || true
fi

echo "Installed AnotherEditor.app to ${INSTALL_DIR}."
echo "Finder can use it through Open With for registered text and source file types."
