#!/bin/bash
# ParkWatch — package postinstall.
# Runs automatically when the .pkg is installed. Handles everything the old
# .command scripts did, with no Terminal window and no security prompts.
set -e

DEST="/Library/Application Support/ParkWatch"
APP="$DEST/app"

# The pkg payload lands in $DEST; make sure the pieces are runnable.
chmod +x "$APP/bridge/parkwatch_native_host" 2>/dev/null || true
xattr -dr com.apple.quarantine "$DEST" 2>/dev/null || true

# Register the native messaging host for every Chrome-family browser of every
# user on this Mac. Installing per-user (rather than system-wide) keeps it
# working without elevated privileges later.
EXT_ID="__EXT_ID__"

register_for_user() {
  local home="$1"
  local user="$2"
  local registered=0
  for appdir in \
    "$home/Library/Application Support/Google/Chrome" \
    "$home/Library/Application Support/Google/Chrome Beta" \
    "$home/Library/Application Support/Chromium" \
    "$home/Library/Application Support/BraveSoftware/Brave-Browser" \
    "$home/Library/Application Support/Microsoft Edge"; do
    if [ -d "$appdir" ]; then
      mkdir -p "$appdir/NativeMessagingHosts"
      cat > "$appdir/NativeMessagingHosts/com.parkwatch.bridge.json" <<JSON
{
  "name": "com.parkwatch.bridge",
  "description": "ParkWatch UDP/telnet bridge",
  "path": "$APP/bridge/parkwatch_native_host",
  "type": "stdio",
  "allowed_origins": ["chrome-extension://$EXT_ID/"]
}
JSON
      chown "$user" "$appdir/NativeMessagingHosts/com.parkwatch.bridge.json" 2>/dev/null || true
      registered=1
    fi
  done
  return 0
}

# $USER isn't reliable in a pkg context; walk real home directories instead.
for home in /Users/*; do
  [ -d "$home" ] || continue
  case "$(basename "$home")" in
    Shared|Guest) continue ;;
  esac
  register_for_user "$home" "$(basename "$home")"
done

# Leave the finish-guide where the user can find it, and open it.
GUIDE="$DEST/Finish Installing ParkWatch.html"
if [ -f "$GUIDE" ]; then
  CONSOLE_USER=$(stat -f "%Su" /dev/console 2>/dev/null || echo "")
  if [ -n "$CONSOLE_USER" ] && [ "$CONSOLE_USER" != "root" ]; then
    su - "$CONSOLE_USER" -c "open '$GUIDE'" 2>/dev/null || true
    su - "$CONSOLE_USER" -c "open -a 'Google Chrome' 'chrome://extensions/'" 2>/dev/null || true
    su - "$CONSOLE_USER" -c "open -R '$APP'" 2>/dev/null || true
  fi
fi

exit 0
