#!/bin/bash
# Jenico-VPN launcher: a normal double-clickable Mac app. On first run (or when
# this app is newer than the installed daemon) it asks for the admin password
# ONCE via the native macOS dialog and installs/updates the root service; then
# it just opens the gold UI. The daemon self-updates via OTA afterwards, so the
# password prompt effectively appears only on first install.
RES="$(cd "$(dirname "$0")/../Resources" && pwd)"
DEST=/usr/local/jnqj-vpn
APPV="$(cat "$RES/VERSION" 2>/dev/null)"
CURV=""
[ -x "$DEST/vpnclient" ] && CURV="$("$DEST/vpnclient" version 2>/dev/null | awk '{print $NF}')"

need=0
if [ ! -f /Library/LaunchDaemons/net.jnqj.vpn.plist ] || [ -z "$CURV" ]; then
  need=1
elif [ "$CURV" != "$APPV" ]; then
  # Install only when the app is NEWER than the daemon — the daemon OTAs ahead
  # of this app copy, and re-running the app must never downgrade it.
  lowest="$(printf '%s\n%s\n' "$APPV" "$CURV" | sort -V | head -1)"
  [ "$lowest" = "$CURV" ] && need=1
fi

if [ "$need" = 1 ]; then
  /usr/bin/osascript \
    -e 'on run argv' \
    -e 'do shell script ("/bin/bash " & quoted form of item 1 of argv & " " & quoted form of item 2 of argv) with administrator privileges with prompt "Jenico-VPN 需要安装后台服务（仅首次）"' \
    -e 'end run' \
    "$RES/install-core.sh" "$RES" || exit 1
fi

# Wait for the daemon's UI to come up, then open it — preferring a fixed-size
# (452x858) chromeless Chrome/Edge app window to match the PC client's portrait
# default, falling back to the default browser (Safari) if neither is installed.
# The dedicated --user-data-dir is what makes --window-size actually apply even
# when the user already has Chrome/Edge open (startup flags are otherwise ignored
# by the existing instance), and keeps our window out of their browsing session.
for i in $(seq 1 60); do
  curl -s -o /dev/null --max-time 1 "http://127.0.0.1:8899/" && break
  sleep 0.5
done
URL="http://127.0.0.1:8899/"
DD="$HOME/Library/Application Support/Jenico-VPN/win"
BIN=""
for c in "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" \
         "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"; do
  [ -x "$c" ] && { BIN="$c"; break; }
done
if [ -n "$BIN" ]; then
  "$BIN" --app="$URL" --window-size=452,858 --user-data-dir="$DD" \
    --no-first-run --no-default-browser-check >/dev/null 2>&1 &
else
  open "$URL"
fi