#!/bin/sh
# Downloads and installs TurkishAutocorrect without the Gatekeeper
# "Open Anyway" dance. Safe to read before running:
#   curl -fsSL https://eicyer.github.io/os-turkish-deasciifier/install.sh | less
#
# Why this skips the security notice: macOS only quarantines files
# downloaded through a browser. A file fetched with curl never gets that
# flag, so there's nothing for Gatekeeper to warn about — this script
# also clears it explicitly (`xattr -cr`) as a safety net in case it
# ever ends up quarantined some other way.
set -eu

REPO="eicyer/os-turkish-deasciifier"
DMG_URL="https://github.com/${REPO}/releases/latest/download/TurkishAutocorrect.dmg"
APP_NAME="TurkishAutocorrect.app"
DEST="/Applications/${APP_NAME}"

TMP_DIR=$(mktemp -d)
MOUNT_DIR=""

cleanup() {
  if [ -n "$MOUNT_DIR" ]; then
    hdiutil detach "$MOUNT_DIR" -quiet >/dev/null 2>&1 || true
  fi
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT

echo "==> Downloading TurkishAutocorrect..."
curl -fsSL "$DMG_URL" -o "$TMP_DIR/TurkishAutocorrect.dmg"

echo "==> Mounting disk image..."
MOUNT_DIR=$(mktemp -d)
hdiutil attach "$TMP_DIR/TurkishAutocorrect.dmg" -mountpoint "$MOUNT_DIR" -nobrowse -quiet

if [ -d "$DEST" ]; then
  echo "==> Quitting the currently installed copy..."
  osascript -e 'tell application "TurkishAutocorrect" to quit' >/dev/null 2>&1 || true
  pkill -x TurkishAutocorrect >/dev/null 2>&1 || true
  sleep 1
  echo "==> Replacing previous version..."
  rm -rf "$DEST"
fi

echo "==> Installing to /Applications..."
cp -R "${MOUNT_DIR}/${APP_NAME}" "$DEST"

echo "==> Clearing quarantine flag..."
xattr -cr "$DEST"

hdiutil detach "$MOUNT_DIR" -quiet >/dev/null 2>&1 || true
MOUNT_DIR=""

echo ""
echo "Installed TurkishAutocorrect to /Applications — no security prompt needed."
echo ""
echo "Next steps:"
echo "  1. Click the dimmed TR icon in the menu bar and check Enabled."
echo "  2. Grant the Accessibility and Input Monitoring prompts macOS shows."
echo ""
open "$DEST"
