#!/bin/sh
# VPNZONE for Linux — one command, full WireGuard tunnel. https://vpnzone.net
# Install + connect:   curl -fsSL https://vpnzone.net/linux.sh | sudo sh
# Disconnect:          curl -fsSL https://vpnzone.net/linux.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/linux.sh | sudo sh"; exit 1; }
if ! command -v wg >/dev/null 2>&1 || ! command -v wg-quick >/dev/null 2>&1; then
  echo "VPNZONE: installing wireguard-tools..."
  if command -v apt-get >/dev/null 2>&1; then apt-get update -qq && apt-get install -y -qq wireguard-tools
  elif command -v dnf >/dev/null 2>&1; then dnf install -y wireguard-tools
  elif command -v pacman >/dev/null 2>&1; then pacman -Sy --noconfirm wireguard-tools
  elif command -v zypper >/dev/null 2>&1; then zypper -n install wireguard-tools
  else echo "VPNZONE: please install wireguard-tools, then re-run."; exit 1; fi
fi
mkdir -p /etc/vpnzone /etc/wireguard
UIDF=/etc/vpnzone/uid; [ -f "$UIDF" ] || cat /proc/sys/kernel/random/uuid > "$UIDF"
VZUID=$(cat "$UIDF")
KEYF=/etc/vpnzone/key
[ -f "$KEYF" ] || { umask 077; wg genkey > "$KEYF"; }
PRIV=$(cat "$KEYF"); PUB=$(printf %s "$PRIV" | wg pubkey)
if [ "${1:-up}" = "down" ]; then
  wg-quick down vpnzone 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 > /etc/wireguard/vpnzone.conf <<CONF
[Interface]
PrivateKey = $PRIV
Address = $ADDR
DNS = $DNS
[Peer]
PublicKey = $SPK
Endpoint = $EP
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
CONF
wg-quick down vpnzone 2>/dev/null || true
wg-quick up vpnzone
echo "VPNZONE: connected via $NODE ($TIER). Ads, trackers & malware are blocked on the server."
echo "Disconnect anytime:  curl -fsSL https://vpnzone.net/linux.sh | sudo sh -s -- down"
