#!/bin/bash
set -euo pipefail

APP_NAME="NeuralBytes Support.app"
DMG_NAME="NeuralBytesSupport-macOS-1.0.1.dmg"
DMG_URL="https://neuralbytes.org/downloads/${DMG_NAME}"
EXPECTED_SHA256="adbb162c64572927f480087d47fdf7272f238e203a8c61b86cec1f25b38ae282"
INSTALL_DIR="${HOME}/Applications"
INSTALL_PATH="${INSTALL_DIR}/${APP_NAME}"
STATE_FILE="${HOME}/Library/Application Support/NeuralBytesSupport/agent-state.json"
WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/neuralbytes-support.XXXXXX")"
MOUNT_DIR="${WORK_DIR}/mount"
DMG_PATH="${WORK_DIR}/${DMG_NAME}"

cleanup() {
  if mount | grep -q "on ${MOUNT_DIR} "; then
    hdiutil detach "${MOUNT_DIR}" >/dev/null 2>&1 || true
  fi
  rm -rf "${WORK_DIR}"
}
trap cleanup EXIT

need_tool() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "Missing required macOS tool: $1" >&2
    exit 1
  fi
}

need_tool curl
need_tool shasum
need_tool hdiutil
need_tool xattr
need_tool ditto
need_tool open

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "This installer is for macOS only." >&2
  exit 1
fi

cat <<'TEXT'
NeuralBytes Support macOS installer

This helper downloads the NeuralBytes Support DMG, verifies its checksum,
copies the app to your user Applications folder, and removes quarantine only
from that NeuralBytes Support app.

It does not disable Gatekeeper globally and does not change system security
settings. Use it only during an approved NeuralBytes support session.
TEXT

printf "\nContinue? [y/N] "
read -r answer
case "${answer}" in
  y|Y|yes|YES) ;;
  *) echo "Canceled."; exit 0 ;;
esac

mkdir -p "${INSTALL_DIR}" "${MOUNT_DIR}"

echo "Downloading ${DMG_NAME}..."
curl --fail --location --show-error --silent "${DMG_URL}" --output "${DMG_PATH}"

echo "Verifying checksum..."
actual_sha="$(shasum -a 256 "${DMG_PATH}" | awk '{print $1}')"
if [[ "${actual_sha}" != "${EXPECTED_SHA256}" ]]; then
  echo "Checksum verification failed." >&2
  echo "Expected: ${EXPECTED_SHA256}" >&2
  echo "Actual:   ${actual_sha}" >&2
  exit 1
fi

echo "Mounting DMG..."
hdiutil attach -nobrowse -readonly -mountpoint "${MOUNT_DIR}" "${DMG_PATH}" >/dev/null

if [[ ! -d "${MOUNT_DIR}/${APP_NAME}" ]]; then
  echo "Could not find ${APP_NAME} in the DMG." >&2
  exit 1
fi

echo "Installing to ${INSTALL_PATH}..."
rm -rf "${INSTALL_PATH}"
ditto "${MOUNT_DIR}/${APP_NAME}" "${INSTALL_PATH}"

echo "Removing any old saved NeuralBytes session token..."
rm -f "${STATE_FILE}" 2>/dev/null || true

echo "Authorizing this app for this Mac user..."
xattr -dr com.apple.quarantine "${INSTALL_PATH}" 2>/dev/null || true

cat <<TEXT

Done.

Enter the one-time support code from your NeuralBytes technician in the app
window. Keep this Terminal window open while support is in progress. When
the app closes, this helper removes the local session token.
TEXT

echo "Opening NeuralBytes Support..."
open -W "${INSTALL_PATH}" || open "${INSTALL_PATH}"

echo "Removing saved NeuralBytes session token..."
rm -f "${STATE_FILE}" 2>/dev/null || true
