#!/bin/sh
# VPNZONE for macOS — one command, full WireGuard tunnel. https://vpnzone.net
# Install + connect:   curl -fsSL https://vpnzone.net/mac.sh | sudo sh
# Disconnect:          curl -fsSL https://vpnzone.net/mac.sh | sudo sh -s -- down
# Free plan: 400 MB every day. Unlimited from $3/month — https://vpnzone.net/#pricing
set -e
CP="https://cyber3-vpn-cp.cyber3.workers.dev"
[ "$(id -u)" = "0" ] || { echo "VPNZONE: run with sudo:  curl -fsSL https://vpnzone.net/mac.sh | sudo sh"; exit 1; }
BREW=/opt/homebrew/bin/brew; [ -x "$BREW" ] || BREW=/usr/local/bin/brew
WG=$(command -v wg || true); WQ=$(command -v wg-quick || true)
for P in /opt/homebrew/bin /usr/local/bin; do
  [ -z "$WG" ] && [ -x "$P/wg" ] && WG="$P/wg"
  [ -z "$WQ" ] && [ -x "$P/wg-quick" ] && WQ="$P/wg-quick"
done
if [ -z "$WG" ] || [ -z "$WQ" ]; then
  [ -x "$BREW" ] || { echo "VPNZONE: install Homebrew first (https://brew.sh), then re-run."; exit 1; }
  RUSER="${SUDO_USER:-$(stat -f %Su /dev/console)}"
  echo "VPNZONE: installing wireguard-tools via Homebrew (as $RUSER)..."
  sudo -u "$RUSER" "$BREW" install wireguard-tools
  for P in /opt/homebrew/bin /usr/local/bin; do
    [ -x "$P/wg" ] && WG="$P/wg"; [ -x "$P/wg-quick" ] && WQ="$P/wg-quick"
  done
fi
PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"; export PATH
mkdir -p /etc/vpnzone
UIDF=/etc/vpnzone/uid; [ -f "$UIDF" ] || uuidgen > "$UIDF"
VZUID=$(cat "$UIDF")
KEYF=/etc/vpnzone/key
[ -f "$KEYF" ] || { umask 077; "$WG" genkey > "$KEYF"; }
PRIV=$(cat "$KEYF"); PUB=$(printf %s "$PRIV" | "$WG" pubkey)
CONF=/etc/vpnzone/vpnzone.conf
if [ "${1:-up}" = "down" ]; then
  "$WQ" down "$CONF" 2>/dev/null || true
  curl -fsS -m 10 -X POST "$CP/disconnect" -H 'content-type: application/json' \
    -d "{\"user_id\":\"$VZUID\",\"client_pubkey\":\"$PUB\"}" >/dev/null 2>&1 || true
  echo "VPNZONE: disconnected."
  exit 0
fi
R=$(curl -fsS -m 20 -X POST "$CP/connect" -H 'content-type: application/json' \
  -d "{\"user_id\":\"$VZUID\",\"client_pubkey\":\"$PUB\"}") || {
  echo "VPNZONE: could not connect. Daily free cap reached? Go Unlimited: https://vpnzone.net/#pricing"; exit 1; }
getf() { printf %s "$R" | sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p"; }
IP=$(getf client_ip); DNS=$(getf dns); SPK=$(getf server_pubkey); EP=$(getf endpoint); NODE=$(getf node); TIER=$(getf tier)
[ -n "$IP" ] && [ -n "$SPK" ] && [ -n "$EP" ] || { echo "VPNZONE: unexpected reply: $R"; exit 1; }
case "$IP" in */*) ADDR="$IP";; *) ADDR="$IP/32";; esac
umask 077
cat > "$CONF" <<WGEOF
[Interface]
PrivateKey = $PRIV
Address = $ADDR
DNS = $DNS
[Peer]
PublicKey = $SPK
Endpoint = $EP
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
WGEOF
"$WQ" down "$CONF" 2>/dev/null || true
"$WQ" up "$CONF"
echo "VPNZONE: connected via $NODE ($TIER). Ads, trackers & malware are blocked on the server."
echo "Disconnect anytime:  curl -fsSL https://vpnzone.net/mac.sh | sudo sh -s -- down"
