#!/bin/bash
# Root-side install/upgrade, invoked by the launcher through the native macOS
# password dialog. Copies the daemon binaries out of the app bundle and
# (re)loads the LaunchDaemon.
set -e
RES="$1"
DEST=/usr/local/jnqj-vpn

launchctl unload /Library/LaunchDaemons/net.jnqj.vpn.plist 2>/dev/null || true
mkdir -p "$DEST"
cp -f "$RES/vpnclient" "$RES/sing-box" "$DEST/"
cp -f "$RES/icon.icns" "$DEST/" 2>/dev/null || true
chmod 755 "$DEST/vpnclient" "$DEST/sing-box"
xattr -dr com.apple.quarantine "$DEST" 2>/dev/null || true

cat > /Library/LaunchDaemons/net.jnqj.vpn.plist <<'PLIST'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>net.jnqj.vpn</string>
  <key>ProgramArguments</key><array><string>/usr/local/jnqj-vpn/vpnclient</string></array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardErrorPath</key><string>/var/log/jnqj-vpn.log</string>
  <key>StandardOutPath</key><string>/var/log/jnqj-vpn.log</string>
</dict></plist>
PLIST
launchctl load /Library/LaunchDaemons/net.jnqj.vpn.plist
exit 0