#!/bin/sh
# SandVPN Linux installer (tarball edition).
# Layout it installs:
#   /usr/local/bin/sandvpn            CLI (runs as your user)
#   /usr/local/bin/sandvpn-service    privileged daemon
#   /usr/lib/sandvpn/{xray,sing-box}  bundled tunnel engines (the daemon
#                                     searches this dir after its own)
# Then registers + starts the daemon as a systemd unit (sandvpn.service).
set -eu

if [ "$(id -u)" -ne 0 ]; then
    echo "Run as root: sudo ./install.sh" >&2
    exit 1
fi

cd "$(dirname "$0")"

# ── Dependencies: auto-install where we can (apt = Debian/Ubuntu), warn
#    elsewhere. A future .deb makes this a proper Depends: instead. ──
MISSING=""
command -v nft >/dev/null 2>&1 || MISSING="$MISSING nftables"
command -v wg-quick >/dev/null 2>&1 || MISSING="$MISSING wireguard-tools"
if [ -n "$MISSING" ]; then
    if command -v apt-get >/dev/null 2>&1; then
        echo "Installing dependencies:$MISSING"
        apt-get update -qq && apt-get install -y -qq $MISSING \
            || echo "WARN: automatic dependency install failed — install manually:$MISSING"
    else
        echo "WARN: missing dependencies (install with your package manager):$MISSING"
    fi
fi
[ -e /dev/net/tun ] \
    || echo "WARN: /dev/net/tun missing — the Xray protocol needs TUN support"

# ── Binaries ──
install -m 755 sandvpn /usr/local/bin/sandvpn
install -m 755 sandvpn-service /usr/local/bin/sandvpn-service
install -d -m 755 /usr/lib/sandvpn
install -m 755 xray /usr/lib/sandvpn/xray
install -m 755 sing-box /usr/lib/sandvpn/sing-box

# ── Daemon (writes the systemd unit, enables and starts it) ──
if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
    /usr/local/bin/sandvpn-service --install
    # `enable --now` leaves an ALREADY-RUNNING service on the old binary —
    # restart so an upgrade actually takes effect.
    systemctl restart sandvpn.service
else
    echo "WARN: systemd not available — start the daemon manually:"
    echo "      sudo /usr/local/bin/sandvpn-service --console &"
fi

echo ""
echo "SandVPN installed. Get started (as your normal user):"
echo "  sandvpn login <email>"
echo "  sandvpn connect <country> [--protocol wireguard|xray] [--killswitch]"
echo "  sandvpn status | disconnect | account"
