#!/bin/sh
# ─────────────────────────────────────────────────────────────────────────────
# Nexabar macOS installer — the target of:
#
#     curl -fsSL https://nexabar.site/install/mac | sh
#
# Downloads the app, installs it to /Applications, and launches it. No Gatekeeper
# prompt and no `xattr -cr` step is needed because curl never sets
# com.apple.quarantine and CLI unzip (ditto) never adds it.
#
# nexabar.site's GET /install/mac serves this file with https://nexabar-delivery.c-viperdevelopment.workers.dev/app-mac
# replaced by the real download URL (see scripts/getnolock-install-route.ts).
# Running this file directly also works if you export NEXABAR_APP_URL first.
# ─────────────────────────────────────────────────────────────────────────────
set -e

DOWNLOAD_URL="${NEXABAR_APP_URL:-https://nexabar-delivery.c-viperdevelopment.workers.dev/app-mac}"
APP="Nexabar.app"                 # release bundle name (PRODUCT_NAME in project.yml)
PROC="Nexabar"                    # executable / process name
STAGE="$(mktemp -d /tmp/nexabar-install.XXXXXX)"
trap 'rm -rf "$STAGE" 2>/dev/null || true' EXIT

B=$(printf '\033[1;34m'); G=$(printf '\033[1;32m'); Y=$(printf '\033[1;33m'); R=$(printf '\033[0m')
step() { printf '%s>%s %s\n' "$B" "$R" "$1"; }
ok()   { printf '%s✓%s %s\n' "$G" "$R" "$1"; }
die()  { printf '\n%s✗ %s%s\n\n' "$Y" "$1" "$R" >&2; exit 1; }

printf '\n%s┌───────────────────────────────┐%s\n'   "$B" "$R"
printf   '%s│        Nexabar installer       │%s\n'   "$B" "$R"
printf   '%s└───────────────────────────────┘%s\n\n' "$B" "$R"

case "$DOWNLOAD_URL" in
  http*://*) : ;;
  *) die "No download URL configured. (Server var NEXABAR_APP_URL is unset.)" ;;
esac

# Preflight: SIP + AMFI must be OFF, or AMFI SIGKILLs the app before main() with no way to explain itself.
# (Setting the amfi boot-arg requires SIP already disabled, so its presence implies both.)
if ! nvram boot-args 2>/dev/null | grep -q "amfi_get_out_of_my_way=1"; then
  die "Setup required: disable SIP + AMFI first, then re-run this command.
     1. Boot into Recovery (Apple Silicon: hold the power button; Intel: hold Cmd-R at startup).
     2. Open Terminal and run:  csrutil disable
     3. Then run:  sudo nvram boot-args=\"amfi_get_out_of_my_way=1\"
     4. Reboot, then paste the install command again."
fi

step "Downloading…"
curl -fSL --retry 3 --retry-delay 2 --progress-bar -o "$STAGE/app.zip" "$DOWNLOAD_URL" \
  || die "Download failed — check your connection and try again."
ok "Downloaded ($(du -h "$STAGE/app.zip" | awk '{print $1}'))"

step "Extracting…"
mkdir -p "$STAGE/x"
/usr/bin/ditto -x -k "$STAGE/app.zip" "$STAGE/x" 2>/dev/null \
  || /usr/bin/unzip -q "$STAGE/app.zip" -d "$STAGE/x" \
  || die "Extract failed."
APP_PATH="$(/usr/bin/find "$STAGE/x" -maxdepth 3 -type d -name "$APP" 2>/dev/null | head -1)"
[ -n "$APP_PATH" ] || die "$APP not found in the download."
ok "Extracted"

step "Quitting any running instance…"
/usr/bin/killall -9 "$PROC" 2>/dev/null || true
sleep 0.3

step "Installing to /Applications…"
DEST="/Applications/$APP"
USR="$(/usr/bin/id -un)"
LSR="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
for oldb in "$DEST".old-* "$HOME/Applications/$APP".old-* "$HOME/Applications/$APP" "$DEST/$APP"; do
  [ -e "$oldb" ] && "$LSR" -u "$oldb" 2>/dev/null || true
done
rm -rf "$HOME/Applications/$APP" "$HOME/Applications/$APP".old-* 2>/dev/null || true
if [ -w "/Applications" ] && { [ ! -e "$DEST" ] || [ -O "$DEST" ]; } && ! ls -d "$DEST".old-* >/dev/null 2>&1 && rm -rf "$DEST" 2>/dev/null && cp -R "$APP_PATH" "$DEST" 2>/dev/null; then
  # /Applications is writable AND no root-owned copy or .old-* leftover is in the way → no password, user-owned.
  :
elif /usr/bin/osascript -e "do shell script \"/bin/rm -rf '$DEST' '$DEST'.old-* '$HOME/Applications/$APP' '$HOME/Applications/$APP'.old-* && /bin/cp -R '$APP_PATH' '$DEST' && /usr/sbin/chown -R '$USR':staff '$DEST'\" with administrator privileges" >/dev/null 2>&1; then
  # Native macOS GUI password/Touch ID prompt replaced the root-owned copy and chowned it to the user.
  :
elif printf '  (replacing a system-owned copy — enter your Mac password)\n' && sudo -v </dev/tty 2>/dev/tty; then
  sudo rm -rf "$DEST" "$DEST".old-* "$HOME/Applications/$APP" "$HOME/Applications/$APP".old-* </dev/tty
  sudo cp -R "$APP_PATH" "$DEST" </dev/tty || die "Install to /Applications failed."
  sudo chown -R "$USR":staff "$DEST" </dev/tty
else
  # Not an admin (or password declined) — fall back to ~/Applications (no sudo needed there).
  DEST="$HOME/Applications/$APP"
  mkdir -p "$HOME/Applications"
  rm -rf "$DEST" 2>/dev/null || true
  cp -R "$APP_PATH" "$DEST" || die "Install failed."
  printf '  Not an admin — installed to ~/Applications instead.\n'
fi
INSTALLED="$DEST"
[ -d "$INSTALLED" ] || die "Install failed."
xattr -cr "$INSTALLED" 2>/dev/null || true
chmod -R +x "$INSTALLED/Contents/MacOS/" 2>/dev/null || true
ok "Installed at $INSTALLED"

step "Launching…"
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -f "$INSTALLED" 2>/dev/null || true
open -n "$INSTALLED" 2>/dev/null || open "$INSTALLED" 2>/dev/null || true

printf '\n%sNexabar is installed.%s Sign in with your nexabar.site account to get started.\n\n' "$G" "$R"
